funfetti funfetti - 21 days ago 5
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:

<?php
session_start();
$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):

$removeditem:
7

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


Am I missing something obvious?

Answer

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)
    unset($_SESSION['stuff'][$k]);
}