1.11M Members

remove single element in session array

 
0
 

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!

 
1
 

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

 
0
 

@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]);
 
0
 

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

 
1
 

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!

 
0
 

You would need to do:

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

And please try to use code tags.

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