PhpRiot
Download This Article
Download this article in PDF format with all listings and files.

Price: $5.00 AUD
(Approx. $4.10 USD)

More information
Browse Articles
Ajax (4), APC (1), CAPTCHA (1), CSS (3), Debugging (1), File Upload (1), Google (3), Google Maps (2), JavaScript (12), JSON (2), MVC (1), MySQL (7), onbeforeunload (1), OOP (1), PHP (28), PhpDoc (1), PostgreSQL (6), Prototype (11), Reflection (1), RFC 1867 (1), Robots (1), Scriptaculous (1), SEO (1), Sessions (1), SimpleXML (1), Smarty (5), SOAP (1), SPL (1), Templates (2), W3C (1), XHTML (1), Zend Framework (1), Zend_Search_Lucene (1)

PhpRiot Newsletter
Your Email Address:

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


Tagged in ,