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

thanks!

@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;
unset($_SESSION['product_id'][$product_id]);

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!

commented: Yes +7

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"]);
unset($_SESSION["product_id"][$index]);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.