This is a tutorial on how to store a PHP array in a session variable. Typically, this sort of design is used on eCommerce websites, where the user is able to add multiple products to their cart. Because the cart is a temporary list, many developers will opt to store it in the user’s session.
Storing an array in a session variable is simple, and it works exactly the same as storing string values or whatnot. Have a look at the following PHP code snippet:
<?php //Start your session. session_start(); //A simple array that contains product IDs. $cartArray = array( 123, 12, 490 ); //Store the array in a session variable called "cart" $_SESSION['cart'] = $cartArray; //Dump out the session variable, just to //see what it looks like. var_dump($_SESSION['cart']);
If you run the code above, you’ll see that our session variable contains the $cartArray. The output of our var_dump will look like this:
array (size=3) 0 => int 123 1 => int 12 2 => int 490
Pretty simple, right?
Looping over the session array.
But what if we want to loop through this cart array?
<?php //Start your session. session_start(); //Make sure that the session variable actually exists! if(isset($_SESSION['cart'])){ //Loop through it like any other array. foreach($_SESSION['cart'] as $productId){ //Print out the product ID. echo $productId, '<br>'; } }
In the code above:
- We make sure that the session variable in question actually exists. This is important, as we can never be sure that a particular session variable has been set. If we attempt to iterate over a session array that does not exist, our application will throw out a number of PHP warnings, such as “Warning: Invalid argument supplied for foreach() “
- We loop through the session array like we would with a regular PHP array. We print out the product ID of the cart item for testing purposes.
To make sure that our session array always exists, we could use the following code:
<?php //Start your session. session_start(); //Check if the session variable exists. if(!isset($_SESSION['cart'])){ //If it doesn't, create an empty array. $_SESSION['cart'] = array(); }
Here, we check to see if “cart” has been set. If not, we create an empty session array.
Adding elements to the array.
So, what if we want to add items to our session array?
<?php //Start your session. session_start(); //Add a product ID to our cart session variable. $_SESSION['cart'][] = 2787376; //Dump it out for example purposes. var_dump($_SESSION);
As you can see – our session array works the exact same way as a regular PHP array. If you run and refresh the script above, you’ll see that a new element is added on every page load. This is what my session looked like after multiple refreshes:
array (size=1) 'cart' => array (size=6) 0 => int 123 1 => int 12 2 => int 490 3 => int 2787376 4 => int 2787376 5 => int 2787376
Hopefully, you found this tutorial to be helpful!