PHP Session Array

In beginning, programmer think whether they can store array or not in PHP session.
Yes, you can store array in php session.

You store values in session for getting it latter on any page of PHP application. session_start() need to be present on that page to get the stored values in session. Store array in session for organizing variables you want to store in session.
Suppose you want to keep some data in session for logged-in user. You can store
all those data simply as

PHP Session Array- Method 1:

$_SESSION['userName']  = 'LoggedinUserName';
$_SESSION['loggedIn']  = true;
$_SESSION['ranking']  = 5;
// Other stuff
$_SESSION['x'] = 'abc';
$_SESSION['y'] = 'def';
// un-comment it for seeing the output of all example here on single page.

If you store all of the data like this then it will mix with various other kind of data.
So, it can be better stored as:

PHP Session Array- Method 2:

$user = array();
$user['userName'] = 'LoggedinUserName';
$user['loggedIn'] = true;
$user['ranking'] = 5;
$_SESSION['user'] = $user;

This is same as:

PHP Session Array- Method 3:

$_SESSION['user']['userName']  = 'LoggedinUserName';
$_SESSION['user']['loggedIn']  = true;
$_SESSION['user']['ranking']   = 5;

All Logged-In user data, which are organized inside array, are in user key of a session variable,
so it is easy to maintain.

Comments are open for an year period. Please, write here on Facebook page.