Array session variables

Good day,

We have a website for purchasing books.
We are making the cart for keeping customers selections.
We are using an array session variable:

<?php session_start();?>
$_SESSION['cart']=array();

Anytime a new item is selected by the customer, both "ProductID’ and ‘Quantity’ are stored in the variable:

array_push($_SESSION['cart'],$ProductID,$Quantity);

For instance, this is the variable after a selection of ProductID=5 and Quantity=2:

Array ( [0] => 5 [1] => 2 )

After all customer selections are in the session variable, how can I work with them? I have to read them for process the order.
I have tried using foreach loops, but it is not working.

Thanks a lot!!

foreach should work.
What did you try?

Ref: http://www.php.net/manual/en/control-structures.foreach.php

Hi Pullo,

I have tried many options, even two nested loops as this is a bidimensional array.
Could you please suggest me how to proceed? I’d like to read values in session array and assign them to variables for using them to go to checkout process and load the purchase information in the database.

Thanks a lot!!

Something like this:

<?php 
$arr = array(1, 2, 3, 4);

// Output whole array
print_r($arr);

// Output individual elements
foreach ($arr as $value) {
  echo $value;
}

Outputs:

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) 
1234

If you can post the actual contents of your array, that would help.

Hi Pullo,

This array stores "ProductID’ and ‘Quantity’ (number of products selected).

For instance, this is the variable after a selection of ProductID=5 and Quantity=2 (it is, 2 units of product number 5):

Array ( [0] => 5 [1] => 2 )

Thanks a lot!

You mean like this:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 6
        )

    [1] => Array
        (
            [0] => 2
            [1] => 1
        )

    [2] => Array
        (
            [0] => 3
            [1] => 4
        )

    [3] => Array
        (
            [0] => 4
            [1] => 2
        )

)

In this case, you can do this:

<?php 
$arr = array(
  array(1,6),
  array(2,1),   
  array(3,4),
  array(4,2) 
);

<pre><?php print_r($arr); ?></pre>

<?php 
foreach ($arr as $product) {
  echo "Product " . $product[0] . ": " . $product[1] . " units<br>";
}

?>

Just noting that in POST#1 you are attempting to set the session key ‘cart’ as an array outside of php.

<?php<?php session_start();?>
$_SESSION[‘cart’]=array();

<?php
session_start();
$_SESSION['cart']=array();
//anyother php code
array_push($_SESSION['cart'],$ProductID,$Quantity);	
//then close php
?> 

Hi Pullo,

I have proceed like you said and now it is working fine!

Two last questions please:
1.- regarding the foreach loop. This sentence is working fine:

foreach ($_SESSION as $product) {

If the session variable is $_SESSION[‘cart’], why the sentence is not working in this case?

foreach ($_SESSION['cart'] as $product) {

2.- Is it correct using array_push instruction to load every product selected by the customer in the cart, or should I use another instruction?

array_push($_SESSION['cart'],$ProductID,$Quantity);

Thanks a lot!!!

Hi Drummin,

Sorry for my lack of accuracy. You are completely right, the problem is I just copied and pasted different parts of the code in the post.
Thanks a lot.

Array_push is not always the best way to add things to an array. For example say you post three items using this method. You might end up with something like this, which is meaningless as you don’t know what the keys/values represent.

Array
(
    [0] => 6
    [1] => 3
    [2] => 5
    [3] => 2
    [4] => 4
    [5] => 4
)

There are many ways to do it but If you process your form placing the product ID as the KEY and the QTY as the value, then you would know WHAT each key/value is. Here’s an example.

if(isset($_POST['item'])):
	$_SESSION['cart']=array();
	foreach($_POST['item'] as $key => $itemID):
		$_SESSION['cart'][$itemID] = $_POST['qty'][$key];
	endforeach;
	
	//echo "<pre>";
	//print_r($_SESSION['cart']);
	//echo "</pre>";
endif;

For display you would again use a foreach statement.

//Display
foreach ($_SESSION['cart'] as $prodID => $qty):
	echo "Item ID: " . $prodID . " Quantity: " . $qty . "<br />\\r";
endforeach;

Output would be something usable like this.

Item ID: 6 Quantity: 3
Item ID: 5 Quantity: 2
Item ID: 4 Quantity: 4

Hi Drummin,

$_SESSION[‘cart’] stores shopping cart selections, it is, it would be receiving additional data only when a new product is selected by the customer.
Each selection is made at a different moment, so storing data in $_SESSION is not all at the same time, just one Item ID and Quantity each time.

Thanks a lot.

Well even if you add them at different times, do you think the key will always be 0 and 1? It probably would be if you don’t control $_SESSION[‘cart’] = array(); as you would wipe out anything you had before. Just noting.

Probably best to check with !isset() so you don’t overwrite what you have.

if(!isset($_SESSION['cart'])):
	$_SESSION['cart'] = array();
endif;

Hi Drummin,

I understand your point. Having Session variable loaded with array_push is not the right way to do it.
Each time a customer selects a new product, ProductID and Quantity are stored in these variables:

$ProductID = $_POST['ProductID'];
$Quantity = $_POST['Quantity'];

Then I need to store them in Session array. How could I do it in a proper way?

Also, could you please explain me a little more about IF ISSET instructions?

I have Session array definition in a previous page. Is it correct?

$_SESSION['cart'] = array();

Thanks a lot!

Isset is a great way to control different aspects of your page. You don’t want to do $_POST processing for example if $_POST is not set, or echo a variable if it is not set. Notice how I wrapped my processing example above with an isset statement? This is a good example. See http://www.php.net/manual/en/function.isset.php It doesn’t really matter where you set your session cart to an array, just that you understand that if that statement is run again it will clear any session cart info that was already stored with the key ‘cart’.

If you only need a product id and quantity then my example should do. Just be sure to wrap that session cart = array section.

Hi Drummin,

I am a little confused. Could you please point me how to properly store $ProductID and $Quantity into the Session variable each time a new product us selected by a customer? I am not working with POST.

Thanks a lot!

How are customers selecting products? A link? It’s pretty common to have an add to cart form that send with POST. How will you control quantity?

Here is a modified version based on a Link like

<a href="?Additem=32">Add to cart</a>
<?php
session_start();
if(isset($_GET['Additem'])):
	if(!isset($_SESSION['cart'])):
		$_SESSION['cart'] = array();
	endif;	
	
	$itemID = (isset($_GET['Additem']) && !empty($_GET['Additem']) ? (int) $_GET['Additem'] : null);
		
	if($itemID !== null):
		$qty = 1;
		$_SESSION['cart'][$itemID] = $qty;
	endif;
	
	//echo "<pre>";
	//print_r($_SESSION['cart']);
	//echo "</pre>";
endif;

//Display
if(isset($_SESSION['cart']) && !empty($_SESSION['cart'])){
	foreach ($_SESSION['cart'] as $prodID => $qty):
		echo "Item ID: " . $prodID . " Quantity: " . $qty . "<br />\\r";
	endforeach;
}else{
	echo "No items in cart";
}
?>

This sets the quantity to one, then at checkout you could allow them to change the quantity.

Great, thanks a lot for your help!