remove single element in session array


Im building a shopping cart

for every product that is clicked, i append them to $_SESSION and put comma

so if producct 1 is clicked, the value of the $_SESSION is 1

then if producct 2 is clicked, the value of the $_SESSION becomes 1,2

and then I explode the array for me to get each element

my problem is

since I am storing this into session,

how to remove a single element from it?

so when I click delete say on product 2

the $_SESSION becomes 1 and not 1,2


Featured Replies in this Discussion

  • You can use ... on an array element to remove it from the array.
    Post Contains: Links

You can use unset on an array element to remove it from the array.

Useful post

@pritaeas - unset requires you knowing the array index, which I'm guessing the OP will not know.

Another option would be to change the way you're storing items in the session to the following:

$_SESSION['product_id'] = array(
    // Product id => Quantity
    1 => 1,
    2 => 3,

Then you can do as @pritaeas says and use unset. You can also increment and decrement product quantities.

$product_id = 2;

I changed the way Im storing the product id to

array_push($_SESSION, $product_id);

then im doing the foreach to retrieve them instead of exploding array wih comma separation

now when I do the array_diff($array, $item_to_delete)

as in:

$_SESSION = array_diff($array, $item_to_delete);

it deletes all the array


I found the answer to my question thanks for your help anyway!

i used array_search then I used the key to delete a certain value from it!


You would need to do:

$_SESSION['product_id'] = array_diff($array, array($item_to_delete));

And please try to use code tags.

$index = array_search($remove_item,$_SESSION["product_id"]);
Question Answered as of 3 Years Ago by blocblue, pritaeas and karthik_ppts
This question has already been solved: Start a new discussion instead
Start New Discussion
Tags Related to this Article