is it possible to have an array in a cookie?

Recommended Answers

All 3 Replies

I don't think its possible. When you set a cookie, setcookie expects parameter 1 and paramter 2 to be a string and not an array.

http://in2.php.net/setcookie Look at example 3 !

You may also set array cookies by using array notation in the cookie name. This has the effect of setting as many cookies as you have array elements, but when the cookie is received by your script, the values are all placed in an array with the cookie's name

mmmmmmm cookies...

<?php
//make a batch of cookies
//pass name of array as $batchName, and the values you wish to store as an array $valueArray
function batch_of_cookies($batchName, $valueArray)
{	
	foreach($valueArray as $key=>$val)
	{
		//put cookies in the jar
		setcookie($batchName . "[$key]" , $val);
	}
}

//name cookie
$cookieName = 'myCookie';

//create cookie types
$myCookies= array('chocolate chip' , 'oatmeal' , 'oreo' , 'snicker doodle');

//bake the cookies
batch_of_cookies($cookieName , $myCookies);

///-----------------------------------------------------------------------------------------

//look for cookie in the jar
if(isset($_COOKIE[$cookieName ]))
{	
	//mmm lots of cookies
	foreach($_COOKIE[$cookieName] as $val)
	{
		//take the cookie from the jar
		echo $val;
		echo '<br/>';
	}
}


?>

nav33n and php.net are right, and example 3 works...just needed a touch up to be useful.

first try to serialize your array and after that put it in the cookie. when you have to get it from the cookie and work with it you have to unserialize.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.