Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder d'Anconia's Avatar
    Join Date
    Jan 2010
    Tempe, AZ
    Thanked 6 Times in 6 Posts

    Looping Through Variable within $_SESSION Variable

    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:
    PHP Code:
     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.
    Datagonia Web (My Portfolio)

    Powerful ideas for all lovers of personal and political freedom:
    Freedomain Radio
    Free Talk Live

  2. #2
    Regular Coder Redcoder's Avatar
    Join Date
    May 2012
    Thanked 49 Times in 48 Posts
    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.

    PHP Code:
    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


Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts