funfetti funfetti - 1 year ago 66
PHP Question

Removing items from a session

I'm having trouble removing items in a session array in a shopping cart project. The following code should take the selected item and remove it from the session. However the end result is just the same session as before with nothing removed. I've seen similar problems by googling, but haven't found a working solution yet. Here is the stripped down code:

$removeditem = $_GET['item']; // this identifies the item to be removed
unset($_SESSION['stuff'][$removeditem]); // "stuff" is the existing array in the session

Here are what print_r gives for the following (using "7" as the example of the removed item):


$_SESSION['stuff'] (before and after removal)
[0] => 7
[1] => 24
[2] => 36

Am I missing something obvious?

Answer Source

You are deleting the item with the KEY being equal to $removedItem. It seems to me from your example that you are trying to delete the element that has the VALUE equal to removedItem. In this case, you need to do a foreach loop to identify the key and then delete it.

foreach($_SESSION['stuff'] as $k => $v) {
  if($v == $removeditem)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download