开发者

Deleting first item of a $_COOKIE array

if I add an item to the $_COOKIE array as such:

setcookie("favorites[]", "value",  time()+3600);   

I can delete any item from the $_COOKIE[favorites] array like this:

setcookie("favorites[开发者_开发问答$deletekey]", "", time()+3600);  

EXCEPT the first one added so this does not work:

setcookie("favorites[0]", "", time()+3600*24);  

How can I delete the first one and leave others intact?


If you know how arrays work, you'd know that 0 is actually a key.

$myarray = array("key" => "value", 1 => "one");

$myarray[0] does not exist because that key is not defined. Only the elements $myarray['key'] and $myarray[1] exist in this array. You cannot reference $myarray['key'] as the first item in the array, because 0 is seen as a key for the array and there is no value defined for that key.

You can, however, use PHP's array_values() function to create an array of the values (it basically removes the keys) and reference them that way, but with cookies I don't see how this would be of any use.


I can delete any item from the $_COOKIE[favorites] array like this:

No - when the response is sent back to the browser it should overwrite the current value.

If you want to delete an item from the cookies array do this:

 unset($_COOKIE['favorites']);

If you want to delete a cookie on the browser set the cookie with the same name (and path, and domain) but an expiry date in the past.

There is no such thing as a cookie arry client side - you're confusing PHPs syntax for adding items to an array with how HTTP works. It may be that when the request comes back, PHP will create an array from a cookie named 'favourites[]' but there is no such array on the client - just a single value.

setcookie("favorites[]", "value",  time()+3600); 

creates a cookie named 'favourites[]' which is why its not changed by:

setcookie("favorites[0]", "", time()+3600*24);  

Although it would be valid to create new cookies by appending (or embedding) an integer into a string you should avoid using square brackets.

C.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜