Jump to content

foreach with session variables containing an array


Phaelon
Go to solution Solved by DrMath,

Recommended Posts

Hi all,

I have multiple session varriables:

$_SESSION['cart']['content']['product1']
$_SESSION['cart']['content']['product2']
$_SESSION['cart']['content']['product3']

These have array data in them, such as (productnumber = 1, size = 3)

How can I do a foreach for each of these variables and then using the array data within? Do I do?:

foreach ($_SESSION['cart']['content'] as $content) {
    echo $content['productnumber'];
    echo $content['size'];
}

Link to comment
Share on other sites

You need to go one step further I think. The way you have it now, the only thing $content can have is ['productx']. You need to go all the way to the product to get info about it.

Edited by DrMath
Link to comment
Share on other sites

I can;t do that because the variable names are variable themself, so I can't hardcode their names in. So i am hoping there is a way for PHP to detect them and perform functions on their array

Edited by Phaelon
Link to comment
Share on other sites

  • Solution

You might try to get the key for each one? So

foreach ($_SESSION['cart']['content'] as $key => $content) {
    echo $content['productnumber'];
    echo $content['size'];
}

You may also want to look at http://www.php.net/manual/en/function.array-keys.php This function might be able to help. If you get a list of the array keys of the very last items (the products) then you could do a foreach on that array.

Edited by DrMath
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.