sasori
sasori

Reputation: 5455

how to remove a particular key => value from a session array?

let's say i have $_SESSION['cart']; when I print this

echo "<pre>",print_r($_SESSION['cart']),"</pre>"; 

it will show something like

Array
(
    [1] => 2
    [2] => 2
)

where the keys are the product IDs and the value is the quantity of each product. so, if I would want to delete product no. 2 from that session array, how am to do that ?

I tried the fastest function that came to my mind

 public function removeItem($id2){
   foreach($_SESSION['cart'] as $id => $qty) {
        if ($id == $id2){
         unset($_SESSION['cart'][$id]);

      }
   }
 }

it deleted the whole $_SESSION['cart'] data :(

Upvotes: 1

Views: 3985

Answers (4)

davogotland
davogotland

Reputation: 2777

just do

public function removeItem($id){
    unset($_SESSION['cart'][$id]);
}

Upvotes: 0

Vapire
Vapire

Reputation: 4578

Why are you looping through? If you get the id you want do delete as a parameter anyway, you can do this:

public function removeItem($id2) {
  unset($_SESSION['cart'][$id2]);
}

Upvotes: 2

wikp
wikp

Reputation: 1203

unset($_SESSION['cart'][$id2]);

You don't need to walk through whole array in foreach for this. Simple is better than complicated :)

Upvotes: 4

Dax
Dax

Reputation: 2185

If you want to clear the id just do :

$_SESSION['cart'][$id] = null;

Hope this help

Upvotes: 1

Related Questions