Tuesday, April 21, 2009

How to store an array in a session?

Sometimes it's necessary to temporarily store data specific to a particular user while he/she surfs our website. For example, to make an admin control panel we have to check the admin session in every page.. PHP sessions provide you with just such a facility. We can store an array in a session variable. store multiple values with one reference we can use arrays, and can store these arrays in sessioon.
Sample code
<?php
session_start();
$_SESSION['admin']=array('adid'=>1,'adname'=>'main admin','privilage'=>'super','lastlogin'=>'12-May-2008');
?>
The above code will assign the array values to the session named 'admin'.
To view the array content
<?php
echo "<pre>";
print_r($_SESSION['admin']);
echo "</pre>";
// To get a particular element
echo "<pre>";
print_r($_SESSION['admin']['adname']);
echo "</pre>";
?>

To get all the values from the session array. This loop will list all elements in the session array.So we can use all these values using only one session.
<?php
foreach($_SESSION['admin'] as $key=>$value)
{
// it will print out the values
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
}
?>

The output is :
The value of $_SESSION['adid'] is '1'
The value of $_SESSION['adname'] is 'main admin'
The value of $_SESSION['privilage'] is 'super'
The value of $_SESSION['lastlogin'] is '12-May-2008'