Discuss the detail of cookie access array in cookie of php

  • 2020-06-07 04:20:32
  • OfStack

cookie cannot store arrays by default, so the following is incorrect.
The error is as follows:
Warning: setcookie() expects parameter 2 to be string, array given in
But PHP can parse an cookie with the same name ending in [] into an array. The method of cookie array storage in php is as follows:

Method 1: Serialize the array with serialize, store it in COOKIE, and use unserialize to get the original array when you read it out

Method 2: Set the multi-key value cookie, note that the key must be given

$arr = array(1,2,3);   
setcookie("a[0]", $arr[0]);   
setcookie("a[1]", $arr[1]);   
setcookie("a[2]", $arr[2]);  

Result: All elements of the array are saved.
Array length: 3
Array ( [0] = > 1 [1] = > 2 [2] = > 3 )

The following is incorrect:

$arr = array(1,2,3);   
setcookie("a[]", $arr[0]);   
setcookie("a[]", $arr[1]);   
setcookie("a[]", $arr[2]);  

Result: Only the last element is saved
Array length: 1
Array ( [0] = > 3 )

Related articles: