Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8177965
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T23:39:14+00:00 2026-06-06T23:39:14+00:00

This has me stumped. print_r displays the correct array indices and values, but the

  • 0

This has me stumped. print_r displays the correct array indices and values, but the foreach construct retrieves erroneous values and even changes the value for the last index even though I’m not retrieving the values by reference (not using the ampersand).

<?php

require './includes/dbal.php';
require './includes/user.php';
require './includes/book.php';

session_start();

$title='My Shopping Cart';
include './template/header.php';

if(!isset($_SESSION['user']))
{
    die('You are not logged in.');
}

if(!isset($_SESSION['cart']))
{
    $_SESSION['cart'] = array();
}

if(isset($_POST['submit']) && strcmp($_GET['mode'], 'add') == 0)
{
    if(filter_var($_POST['qty'], FILTER_VALIDATE_INT) == FALSE)
    {
        echo '<div style="color: red;">Invalid quantity specified. Please go back and use a valid quantity.</div>';
    }
    else
    {
        $_SESSION['cart'][$_POST['book_id']] = $_POST['qty'];
    }
}

else if(isset($_POST['update']) && strcmp($_GET['mode'], 'update') == 0)
{
    foreach($_SESSION['cart'] as $key => &$value)
    {
        if((int) $_POST["qty_$key"] === 0)
        {
            unset($_SESSION['cart']["$key"]);
        }
        else
        {
            $value = $_POST["qty_$key"];
        }
    }
}

echo '<h3>Your shopping cart</h3>';

$db = new DBal();
$total=0;
echo '<div id="cart-items"><ul><form action="./cart.php?mode=update" method="post">';

// echo 'Original array: '; print_r($_SESSION['cart']);
foreach($_SESSION['cart'] as $key => $value)
{
    // echo '<br />$key => $value for this iteration: ' . "$key => $value<br />";
    // print_r($_SESSION['cart']);
    $b = new Book($key, $db);
    $book = $b->get_book_details();
    $total += $value * $book['book_nprice']
?>
<li>
    <div><img src="./images/books/thumbs/book-<?php echo $book['book_id']; ?>.jpg" title="<?php echo $book['book_name']; ?>" /></div>
    <span class="cart-price">Amount: Rs. <?php echo $value * $book['book_nprice']; ?></span>
    <h3><?php echo $book['book_name']; ?> by <?php echo $book['book_author']; ?></h3>
    Price: Rs. <?php echo $book['book_nprice']; ?><br /><br />
    Qty: <input type="number" name="qty_<?php echo $book['book_id']; ?>" maxlength="3" size="6" min="1" max="100" value="<?php echo $value; ?>" /><br />
</li>
<?php } echo "<span class=\"cart-price\">Total amount: $total</span>" ?>
<br />
<input type="submit" name="update" value="Update Cart" />
</form></ul></div>

<?php include './template/footer.html'; ?>

Sample output after pressing the update button is like this :

Original array:
Array (
    [9] => 6
    [8] => 7
    [3] => 8
)

$key => $value for this iteration: 9 => 6
Array (
    [9] => 6
    [8] => 7
    [3] => 6
)

$key => $value for this iteration: 8 => 7 
Array (
    [9] => 6
    [8] => 7
    [3] => 7
)

$key => $value for this iteration: 3 => 7 
Array (
    [9] => 6
    [8] => 7
    [3] => 7 
)

The value for the last index gets changes to the value of the current index in every iteration. This results in the last value output having the same value as the second-to-last index.

Help?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T23:39:15+00:00Added an answer on June 6, 2026 at 11:39 pm

    You were using &$value as reference before:

    foreach($_SESSION['cart'] as $key => &$value)
    

    The variable continues to exist as reference beyond the loop, using it again in a loop has expected but non-obvious side effects. This is even mentioned in a big red box in the manual. unset($value) after the first loop to avoid that.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This has got me completely stumped: print_r($json); echo json_encode($json); output: Array ( [query] =>
This is probably a very simple question for some, but it has me stumped.
This is probably a very simple question for some, but it has me stumped.
I'm admittedly a straight-C newbie, but this has got me stumped. I'm working on
This has me stumped. The follow code returns ,,,,,,: <script type=text/javascript> $(function() { $('#listB').sortable({
This one has me stumped. <div id=container> <div id=store></div> <div id=contact></div> </div> I'm looking
This one has me stumped. Here are the relative bits of code: public AgencyDetails(Guid
This one has me stumped. I need to call an activity method from within
I'm really stumped by this one! The StackFrame object ( MSDN Link ) has
This has probably something to do with my transformations, but right now I can't

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.