Storing and retrieving an array in a PHP cookie Storing and retrieving an array in a PHP cookie arrays arrays

Storing and retrieving an array in a PHP cookie


Use json_encode / json_decode to get / set arrays in cookies.

Test array

$cardArray=array(    'CARD 1'=>array('FRONT I', 'BACK I'),    'CARD 2'=>array('FRONT 2', 'BACK 2'));

convert and write the cookie

$json = json_encode($cardArray);setcookie('cards', $json);

the saved string looks like this

{"CARD 1":["FRONT I","BACK I"],"CARD 2":["FRONT 2","BACK 2"]}

get the cookie back

$cookie = $_COOKIE['cards'];$cookie = stripslashes($cookie);$savedCardArray = json_decode($cookie, true);

show the restored array

echo '<pre>';print_r($savedCardArray);echo '</pre>';

outputs

Array(    [CARD 1] => Array        (            [0] => FRONT I            [1] => BACK I        )    [CARD 2] => Array        (            [0] => FRONT 2            [1] => BACK 2        ))

Edit
If you wonder about stripslashes, it is because the string saved actually is

{\"CARD 1\":[\"FRONT I\",\"BACK I\"],\"CARD 2\":[\"FRONT 2\",\"BACK 2\"]}

setcookie adds \ before quoutes to escape them. If you not get rid of those, json_decode will fail.


Edit II

To add a new card to the cookie

  1. load the array as above
  2. $savedCardArray['CARD XX']=array('FRONT XX', 'BACK XX');
  3. save the array as above, but now of course $savedCardArray and not $cardArray.


Serialize/Unserialize works as a simpler alternative to json_encode / json_decode

setcookie('cookiename', serialize(array), ...) to save to cookie.

array = unserialize($_COOKIE['cookienam']) to retrieve array.


Play with something like this

<?php$card_id = '123';$value = 'im a black lady';setcookie("card[$card_id][front]", $value);// reload page to actually read the cookieecho $_COOKIE['card'][$card_id]['front']; // im a black lady?>