PHP Unset issues array cookies

I use this code to set cookie:

$id  = "5623"
$qty = "5";
setcookie("cart[$id]", $qty, time() + (86400 * 30), "/");

After running this code: print_r($_COOKIE);, I get:

Array
(
    [cart] = Array
        (
            [5623] = 4
        )

)

Which is correct. But when I want to UNSET (remove) only the 5623 one and I try ANY the codes below, it does not work:

unset( $_COOKIE["cart[5623] );
unset( $_COOKIE["cart["5623"] );
unset( $_COOKIE["cart"]["5623"] );

When I run the 3 unset rows and in same script try to read all cookies after it doesn’t display any. So I’m like ok great it worked. But when I remove the unset lines and only run script that shows ALL cookies, it still shows up again :S

Any help would be sooo appreciated!!

Answer

Try

$id  = "5623";

if (isset($_COOKIE["cart[$id]"])) {
    unset($_COOKIE["cart[$id]"]);
    setcookie("cart[$id]", "", time()-10, "/");
}

You’re setting the expiry in the past, so the cookie immediately expires, and also clearing the browser cookie file for good measure 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *