Reputation: 45
I have a session array for shopping cart, but the problem is when I try to remove the selected item with UNSET command it seems not working. Somebody please help me. I like to remove the item based on product ID and Size, because some other item in my shopping cart may have same product ID with the different size. Here's my code below :
My shopping cart session structure :
$_SESSION['cart_items'][$id.'-'.$size] = array('id'=> $id,'code' => $code, 'Quantity' => $quantity, 'Size' => $size);
coding for delete item :
$size = $_GET['Product_Size'];
$id = $_GET['Product_ID'];
echo $id.$size;
if(!isset($_SESSION['cart_items'])){
echo "<script type='text/javascript'>alert('Shopping list is empty!');
window.history.back();</script>";
}
if (isset($_SESSION['cart_items'])) {
//print_r($_SESSION['cart_items']);
foreach ($_SESSION['cart_items'] as $key => $value) {
if ($key == $id.'-'.$size) {
unset($_SESSION['cart_items'][$key]);
//print_r($_SESSION['cart_items']);
echo "<script type='text/javascript'>alert('Successful remove!');
window.history.back();</script>";
break;
}
else
{
echo "<script type='text/javascript'>alert('Not found!');
window.history.back();</script>";
}
}
}
Upvotes: 2
Views: 2082
Reputation: 1675
In the foreach
loop syntax you've made a logical mistake, the contents of the $_SESSION['cart_items']
is an array having some keys and values, the keys are in the $id-$size
format, and the values are arrays containing more information. So the "keys" are what you should to check against, Change your code as follows:
foreach ($_SESSION['cart_items'] as $key => $value) {
if ($key == $id.'-'.$size) {
unset($_SESSION['cart_items'][$key]);
// ... (the rest of the code)
Upvotes: 1