Page 1 of 1

How to store an Array in a Session in php

Posted: Sat Dec 18, 2010 5:37 pm
by Saman
Let’s create a new page1.php with the following code:

Code: Select all

<?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 page.

Code: Select all

<?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.

Browser output from 2nd page.

Code: Select all

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 2nd page file looked like this.

Code: Select all

<?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.

You can basically store almost everything on sessions with php. File pointers, objects, etc...