Reputation: 1828
I have the following array:
Array ( [0] => 1 [1] => 1 [2] => 3 [3] => 6 )
and I would like to store it in a cookie. This is the code I tried:
$cart_array = Array ( [0] => 1
[1] => 1
[2] => 3
[3] => 6 );
setcookie('cart_array',$cart_array,time()+3600);
when I display the contents of the cookie using print_r($_Cookie)
, this is what I get:
Array ( [cart] => Array ( [0] => 6 [id] => 2 ) [_ga] => GA1.1.499529088.1424453778 [PHPSESSID] => aj8p5l5ph77n04tab50i83ie34 )
instead of the array I inserted to cookie. Please assist
Upvotes: 0
Views: 1810
Reputation: 5665
Use serialize()
setcookie('cart_array',serialize($cart_array),time()+3600);
$cart_array = unserialize($_COOKIE['cart_array']);
Depending on special characters that may arise (not likely, but good to know if you do) you may also need urlencode()
:
setcookie('cart_array',urlencode(serialize($cart_array))),time()+3600);
$cart_array = unserialize(urldecone($_COOKIE['cart_array']));
Upvotes: 0
Reputation: 4869
I think you're looking for serialize:
<?php
$a = array(1 => 'a', 2 => 'b', 3 => 'c');
$b = serialize($a);
var_dump($b); ////Returns this string(42) "a:3:{i:1;s:1:"a";i:2;s:1:"b";i:3;s:1:"c";}"
$c = unserialize($b);
print_r($c); //Return the same thing as $a
Try out this code, you use serialize to convert an array to string and then you can easily store it. Then, you unserialize to have the array back !
Doc: http://php.net/manual/fr/function.serialize.php
Upvotes: 1
Reputation: 1631
Use this:
setcookie('cart_array',implode('|',$cart_array),time()+3600);
Use this to read cookie back to array:
$cart_array = explode('|',$_COOKIE['cart_array'])
Although I don't think its really necessary to do that. but, just answering your question.
And please be careful to the total length of the Cookie What is the maximum size of a cookie
Upvotes: 0
Reputation: 2815
Cookies does not work with arrays - they are only strings on the local computer. With
$res = serialize($arr);
you can convert an array to a string. (Convert it back with unserialize($arr).)
Upvotes: 0