Daniel Dimitrow Daniel Dimitrow - 3 months ago 18
PHP Question

setcookie() is not working properly

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

Answer
  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;
    }
}