View Full Version : Looping Through Variable within $_SESSION Variable

11-17-2012, 05:32 PM
I am attempting to create an ecommerce site from scratch so that I can include it in my portfolio and eventually apply for an entry-level web development job and I am running into an issue regarding the $_SESSION.

When a user adds an item to their cart I am having the script loop through the $_SESSION elements that look like $_SESSION['item_x'] where 'x' is a number. Once it finds an unused number then I want that variable to be set equal to the product_id.

For example if there were nothing already in the cart then, assuming 'x' starts at 0, $_SESSION['item_0'] would be set equal to the product_id that is being added to the cart.

Currently my code looks like this:

while(isset($_SESSION['item_' . $n])) { //while this session item is set
$n++; //increase the number 'n'
} //exit once arrive at unused session item

//create variables for added product information
$new_product_id = $_SESSION['item_' . $n] = $_POST['product_id'];
$new_product_quantity = $_SESSION['item_' . $n . '_qty'] = 1;

Note that for every $_SESSION['item_x'] that I am also trying to set a $_SESSION['item_x_qty'], so I am setting these two variables as pairs. Would it be easier if I just set one variable that had two values in it with a delimiter in between (for instance '$$' or '&&' or something similar)?

Any help would be appreciated. If I am making this much more difficult than is necessary then please let me know.

11-18-2012, 09:28 AM
Both will work just fine. But the delimiter option involves less code for the same amount of logic when calculating the products in the cart and total cost at the end. e.g $_SESSION['items'][] = $item_product_no.",".$item_quantity.

Also, instead of using something like - $_SESSION['item_' . $n] --> $_SESSION['item_1'], instead add another dimension to make retrieval even easier at the end. For example: $_SESSION['items'][$i] --> $_SESSION['items'][1]

A simple foreach will make it easy to retrieve it.

foreach($_SESSION['items'] as $key->$value)

//Code to separate from dilimeters compute stuff

$product = explode('',", $value);

$product_no = $product[0];
$product_quantity = $product[1];

//Rest of code to manipulate values