How to set and get session variables

How to set and get scalar variables

Set a variable in a session

$_SESSION['product_code'] = 'MBT-1753';

Get a variable from a session

$product_code = $_SESSION['product_code'];

How to set and get arrays

Set an array in a session

if (!isset($_SESSION['cart'])) { 
  $_SESSION['cart'] = array(); 
}

Add an element to an array that’s stored in a session

$_SESSION['cart']['key1'] = 'value1'; 
$_SESSION['cart']['key2'] = 'value2';

Get and use an array that’s stored in a session

$cart = $_SESSION['cart']; 
foreach ($cart as $item) { 
  echo("<li>$item</li>\n");
}

How to remove variables from a session

Remove a session variable

unset($_SESSION['cart']);

Remove all session variables

$_SESSION = array();

Description

Back