Question

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?

Was it helpful?

Solution

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]);
}

OTHER TIPS

You need to first get the key of the element and then unset it. Here's the code you should use:

if(($key = array_search($removeditem, $_SESSION['stuff'])) !== FALSE)
     unset($_SESSION['stuff'][$key]);

The most simple way is:

<?php

    session_start();
    $removeditem = $_GET['item'];

    $temp = array_flip($_SESSION['stuff']);

    unset($_SESSION['stuff'][$temp[removeditem]]);

?>

P.S. Not tested... just a concept.

7 is value in the array not a key, so unsetting something with key 7 will not do a job. What you have to do is compare each item in the array with one you want to delete ($_GET['item']) , retrive its key and unset it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top