• PHP: foreach forbids changes

    Posted on 2009-10-13, 10:53:34 Tags: all, web development

    These couple of weeks I've been busy with a web shop project for a course which addresses security vulnerabilities to web applications. During the course of this project I stumbled upon quite a few problems related to PHP. One of them is the foreach statement.

    I have a cart which stores all items added by a user. Each item has a number of attributes like name, price and amount and its key is the item's ID. To get the name of an item with ID 1, it looks like the following, $_SESSION['cart'][1]['name'].

    Now everytime a user adds an item I use a foreach statement to loop through the array and if the chosen item already is in the list I add that item's amount with 1. It might look like the following:

    foreach($_SESSION['cart'] as $key=>$item) { if($_GET['pid'] == $key) { $item['amount']++; break; } }

    But the above code wouldn't work because when modifying a value in the list like this, $item['amount']++, it won't update the corresponding element in $_SESSION['cart'] variable. I reason it like foreach only returns a copy of the element in $_SESSION['cart'] and that is why it won't change the original element in $_SESSION['cart']. So to fix this I had to update $_SESSION['cart'] directly.

    foreach($_SESSION['cart'] as $key=>$item) { if($_GET['pid'] == $key) { $_SESSION['cart'][$key]['amount']++; $found = TRUE; break; } }

    This fault in code caused me 20 minutes of debugging. It wasn't entirely obvious for me what fault it was when the amount just wouldn't update no matter what I pressed on the website.


    Bookmark and ShareShare Print this postPrint
Comments (0)

Got something to say or have a question?

Note that you don't have to fill in anything other than the comment if you're logged in.

Name: (required)

Email: (optional | Will not be published)

Website: (optional)

Comment:



  • Links

  • Valid CSS!
  • [Valid RSS]
  • Spread Firefox Affiliate Button
Copyright © 2008-2009 JCHo Blog, Website made by Jia Cherng Ho