How to store and retrieve an array value in a cookie. Cookies can only store string values. You cannot store an array directly into a cookie. In this article, We’ll discuss how to store and retrieve an array value from a cookie.
My previous post related to Cookies.
1. How to create, read, update and delete a cookie in PHP
2. How to set a cookie on multiple subdomains
How to Store an Array Value in a Cookie
For better understanding, let’s create a dummy array. Suppose we want to store this array value in a cookie.
1 2 3 4 5 |
$prod = array( 0 => array(134563, 'philips'), 1 => array(156787, 'videocon'), 2 => array(78654, 'samsung') ); |
Let’s try to set an array value into a cookie and see what happens.
1 |
setcookie('products', $prod); |
If we try to set an array value then a cookie will not be created. To set an array value into a cookie first, we need to convert them into a string .
1 2 3 4 5 |
$prod = array( 0 => array(134563, 'philips'), 1 => array(156787, 'videocon'), 2 => array(78654, 'samsung') ); |
1 |
$prod = json_encode($prod, true); setcookie('products', $prod); |
Now our cookie is set, We can retrieve their value using $_COOKIE global variable.
1 2 3 4 5 |
$prod = $_COOKIE['products']; $prod = stripslashes($prod); // string is stored with escape double quotes $prod = json_decode($prod, true); var_dump($prod); |
We can use a serialize method to convert an array into a string and then store them in a cookie.
1 2 3 4 5 6 7 |
$prod = array( 0 => array(134563, 'philips'), 1 => array(156787, 'videocon'), 2 => array(78654, 'samsung') ); $prod = serialize($prod); setcookie('products', $prod); |
Retrieving a cookie value.
1 2 3 4 5 |
$prod = $_COOKIE['products']; $prod = stripslashes($prod); $prod = unserialize($prod); var_dump($prod); |
I find these two methods helpful for storing array values in a cookie. If you know any better method, you can discuss them in comments.