cookie默认不能存数组,所以下面的写法是错误的。
报错如下:
Warning: setcookie() expects parameter 2 to be string, array given in
但是PHP可以把同名且后面以[]结尾的cookie解析为数组。在php里面实现cookie存数组的方法如下:
方法一:先用serialize序列化数组,再存入COOKIE ,读出来时用unserialize得到原来的数组
方法二:设定多键值cookie,注意必须给键值
$arr = array(1,2,3);
setcookie("a[0]", $arr[0]);
setcookie("a[1]", $arr[1]);
setcookie("a[2]", $arr[2]);
结果:
数组所有元素都存到了。
数组长度 :3
Array ( [0] => 1 [1] => 2 [2] => 3 )
以下写法是
错误的:
$arr = array(1,2,3);
setcookie("a[]", $arr[0]);
setcookie("a[]", $arr[1]);
setcookie("a[]", $arr[2]);
结果:
只存了最后一个元素
数组长度 :1
Array ( [0] => 3 )
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn