0

I can't explain much but I am currently trying to remove a product from shopping cart which is saved in cookie.

if(isset($_GET['remove'])) {
   $remove = $_GET["remove"];
   foreach($cart_saved as $q) {
   if($q == $remove) {
       unset($cart_saved[$q]);
       setcookie("shop_items", json_encode($cart_saved), time() + 36000);
   }
}

The value is deleted from the array but I can't update the cookie

chrki
  • 6,143
  • 6
  • 35
  • 55

2 Answers2

0

You write your cookie each time is why there are a problem. So :

if(isset($_GET['remove'])) {
   $remove = $_GET["remove"];
   foreach($cart_saved as $q) {
   if($q == $remove) {
       unset($cart_saved[$q]);
   }
   setcookie("shop_items", json_encode($cart_saved), time() + 36000);
}
0
  1. You have an error in your loop. You need to use a key of $q as index, not the value stored in $q.
  2. It seems reasonable to break the loop after the value is found

foreach($cart_saved as $key => $q) {
    if($q == $remove) {
        unset($cart_saved[$key]);
        setcookie("shop_items", json_encode($cart_saved), time() + 36000);
        break;
    }
}
user4035
  • 22,508
  • 11
  • 59
  • 94