cookies and arrays in php

Date: 20th October 2007 at 1:27 am | Filed under: development, scripts | Author: Sam Burdge

How to store and retreive arrays using cookies with php:

The first step is to turn the array into a string with each array value seperated by a delimiter. I usually choose an unusual delimiter character such as a vertical bar, as the array values are more likely to contain characters such as comma or slashes. Example:

//set the array
 
$my_arr = array();
 
$my_arr[0] = "blue";
 
$my_arr[1] = "red";
 
$my_arr[2] = "green";
 
//create the list for the cookie
 
$cookie_content = "";
 
foreach($my_arr as $key => $value){
 
$cookie_content .= $value . "|";}
 
//trim the last | from the end
 
$cookie_content = substr($cookie_content, 0, -1);

This will give the variable '$cookie_content' the value 'blue|red|green'. The next step is to create the cookie:

//setting the cookie
setcookie("CookieName", $cookie_content, time()+3600);  /* expires in 1 hour */

More info about setting cookies can be found on the php.net website. Ok, so the third and final part is to retreive the array data back from the cookie:

//turn cookie data back into array
if (isset($_COOKIE['CookieName'])) {
$my_cookie_arr = explode("|", $_COOKIE['CookieName']);

The new array '$my_cookie_arr' will now include the same values as the original array '$my_arr'.

1 Response to “cookies and arrays in php”

  • Comment by c-received
    Date: November 6th, 2007 at 9:54 pm

    Blend your own recipe….

    $a = array(’bg’=>’red’,'tx’=>’blue’,'lk’=>’green’);
    print_r($a);

    $b = implode(”|”,array(’red’,'blue’,'green’));
    print_r($b);

    $c = explode(”|”,$b);
    print_r($c);

Leave a Comment