Cookies in PHP are small data files stored on the client, usually used to access persistent data across pages or domain names. Since cookies can only store text data, you can use some tricks to store array data.
There are two common ways to store arrays in PHP Cookies:
PHP has a built-in function called serialize Function that converts an array or object into a string. You can use this function to serialize an array and then store the serialized string in a cookie. For example:
$data = array("name" => "John", "age" => 30); setcookie("mydata", serialize($data));
When getting Cookie, you can use the unserialize function to deserialize the string into the original array:
$data = unserialize($_COOKIE["mydata"]); echo $data["name"] . " is " . $data["age"] . " years old.";
The advantage of this method is that it can easily store and obtain complex arrays and Object data, but due to the need to serialize and deserialize data, there may be some impact on performance.
Converting arrays to strings is also another common method, using a specific delimiter in the string to Separate array elements. This method requires concatenating each element in the array into a string and then using delimiters to concatenate them together. For example:
$data = array("name" => "John", "age" => 30); $data_str = implode("|", $data); setcookie("mydata", $data_str);
When obtaining Cookie, you can use the explode function to split the string into an array:
$data_str = $_COOKIE["mydata"]; $data_array = explode("|", $data_str); $data = array("name" => $data_array[0], "age" => $data_array[1]); echo $data["name"] . " is " . $data["age"] . " years old.";
The advantage of this method is that the code is simple and easy to understand, and it will not have too much impact on performance. Big impact. However, it is important to note that if the data contains delimiters, you need to escape the delimiters or use other delimiters.
In summary, PHP cookies can only store text data, but arrays can be stored in cookies using serialization or string concatenation methods. When using these methods, you need to pay attention to data type, performance and security issues.
The above is the detailed content of Does php cookie store array?. For more information, please follow other related articles on the PHP Chinese website!