PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

An Introduction To PHP Sessions

Can I Store An Array In A Session?

Sure, this is simply done in the same way as setting regular variables.

Let’s create a new page1.php with the following code:

Listing 11 page1.php
<?php
// begin the session
session_start();
 
// create an array
$my_array=array('cat', 'dog', 'mouse', 'bird', 'crocodile', 'wombat', 'koala', 'kangaroo');
 
// put the array in a session variable
$_SESSION['animals']=$my_array;
 
// a little message to say we have done it
echo 'Putting array into a session variable';
?>

Now that we have the array $my_array in a session variable called $_SESSION['animals'] we can have a look through the array as we choose. Use this snippet to create a new page2.php file:

Listing 12 page2.php
<?php
// begin the session
session_start();
 
// loop through the session array with foreach
foreach($_SESSION['animals'] as $key=>$value)
    {
    // and print out the values
    echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
    }
?>

The result of the above code will show you the session array, with the array keys.

Listing 13 Browser output from page2.php (listing-13.txt)
The value of $_SESSION['0'] is 'cat'
The value of $_SESSION['1'] is 'dog'
The value of $_SESSION['2'] is 'mouse'
The value of $_SESSION['3'] is 'bird'
The value of $_SESSION['4'] is 'crocodile'
The value of $_SESSION['5'] is 'wombat'
The value of $_SESSION['6'] is 'koala'
The value of $_SESSION['7'] is 'kangaroo'

You could of course, simply choose individual array members if your page2.php file looked like this..

Listing 14 page2.php
<?php
// begin the session
session_start();
 
// echo a single member of the array
echo $_SESSION['animals'][3];
?>

This would simply retrieve the value for the 4th member of the array and print bird.

In This Article