Reputation: 5455
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
Reputation: 2777
just do
public function removeItem($id){
unset($_SESSION['cart'][$id]);
}
Upvotes: 0
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
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
Reputation: 2185
If you want to clear the id just do :
$_SESSION['cart'][$id] = null;
Hope this help
Upvotes: 1