如何从会话数组中删除特定的key =>值?

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 :(

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

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

If you want to clear the id just do :

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

Hope this help

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

just do

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