Reputation: 43
I know how to set PHP cookies in an array but can I clear it without a loop?
For example I'm setting these four cookies
// set the cookies
setcookie("cookie[four]", "cookiefour");
setcookie("cookie[three]", "cookiethree");
setcookie("cookie[two]", "cookietwo");
setcookie("cookie[one]", "cookieone");
// after the page reloads, print them out
if (isset($_COOKIE['cookie'])) {
foreach ($_COOKIE['cookie'] as $name => $value) {
$name = htmlspecialchars($name);
$value = htmlspecialchars($value);
echo "$name : $value <br />\n";
}
}
OUTPUT:
four : cookiefour
three : cookiethree
two : cookietwo
one : cookieone
To clear the cookies, i use the following loop
if (isset($_COOKIE['cookie'])) {
foreach ($_COOKIE['cookie'] as $name => $value) {
setcookie ("cookie[".$name."]", "", time() - 1);
}
}
Are there any way I could clear the cookies without a loop? Thanks in advance
Upvotes: 2
Views: 972
Reputation: 1484
Could try
if (isset($_COOKIE['cookie'])) {
setcookie ("cookie", array());
}
or even
if (isset($_COOKIE['cookie'])) {
setcookie ("cookie", array('one'=>'','two'=>'','three'=>'','four'=>'',));
}
if you need the indexes
Upvotes: 1
Reputation: 715
No, you pretty much need to loop through existing cookies as the way to delete/expire a cookie, as you have in your code via setcookie, is one cookie at a time.
Upvotes: 3