I try to store array in cookie this way:

for($i=0;$i<5;$i++)
{
	$field[]='test'.$i;
}
$_COOKIE['field2']=$field;

Is it possible do it that way?
I don't want to store each value of array list store separately. I'd like to store them at once. If I was storing values just to another "normal" variable (not cookie), I would do it this way:

for($i=0;$i<5;$i++)
{
	$field[]='test'.$i;
}
$normalVariable=$field;

Can I use similar method to store to cookies?

    SwigriD wrote:

    Can I use similar method to store to cookies?

    No, for two reasons:

    1. Modifying the $_COOKIE array doesn't modify the cookie (which resides on the client's computer) at all.

    2. To modify a cookie, you use the [man]setcookie/man command, which states that the value should be a string.

    You can store cookie names as arrays, e.g. cookie[one], cookie[two], and so on, and PHP will act as if $_COOKIE['cookie'] is an array.

    Alternatively, you can build an array, [man]serialize/man it, and store that in a simple cookie. Then, on the next page, you'd [man]unserialize/man the data to rebuild the array.

      I like idea of serialize and unserialize, but unserialize of array doesn't work for me.

      bit of serialize:

      for($i=0;$i<5;$i++)
      {
      	$field[]='test'.$i;
      }
      setcookie("field2",serialize($field))
      

      ...and bit of unserialize:

      $cookie = $_COOKIE['field2'];
      $field3 = unserialize($cookie);
      foreach($field3 as $value)
      {
      	echo $value.'<br>';
      }
      

        ...and bit of unserialize:

        $cookie = $_COOKIE['field2'];
        $field3 = unserialize($cookie);
        foreach($field3 as $value)
        {
        	echo $value.'<br>';
        }
        

        works this way:

        $cookie=stripcslashes($_COOKIE['field2']);
        $field3 = unserialize($cookie);
        
        foreach($field3 as $value)
        {
        	echo $value.'<br>';
        }
        

        thank you very much for your advice with serialize 🙂

          Write a Reply...