1
foreach ($_SESSION["products"] as $cart_itm) {      
    $items = $cart_itm["code"]
    . " - " . $cart_itm["qty"]
    . " - "  . $cart_itm["price"]
    . "<br>" ;

    echo $items;
}

I have this code which gets every item from my basket and displays them, the problem is when I try to use this variable elsewhere in my code, it only displays the last item in the array, I realised that this is becasue the for loop keeps overwriting the last value . Is there a way I could put all results into one variable or use the loop to assign them too different variables maybe?

I also tried to put

foreach ($_SESSION["products"] as $cart_itm) {      
    $items .= $cart_itm["code"]
    . " - " . $cart_itm["qty"]
    . " - " . $cart_itm["price"]
    . "<br>" ;

    echo $items;
}

after looking through the forum but that returns me with items is not defined

so I tried to put

$items= ("") 

but still get the final result Any help is appreciated, thanks

1
  • BTW: If you didn't already saw it you can take a tour here: stackoverflow.com/tour and see how the site works Commented Jan 23, 2015 at 18:56

3 Answers 3

5

You can concatenate you variables together, but you have to initialize your variable first.

(Otherwise you can think of something like: 'I want to concatenate this string to nothing', so this is obvious not going to work, that's why you initialize your variable so, you can say: 'I want to concatenate this string to a empty string')

Something like this:

$items = "";
foreach ($_SESSION["products"] as $cart_itm) {      
    $items .= $cart_itm["code"] . " - " . $cart_itm["qty"] . " - "  . $cart_itm["price"] . "<br>" ;
}

Or you can put them in a array with this:

$items = array();
foreach ($_SESSION["products"] as $cart_itm) {      
    $items[] = $cart_itm["code"] . " - " . $cart_itm["qty"] . " - "  . $cart_itm["price"] . "<br>" ;

}

print_r($items);
Sign up to request clarification or add additional context in comments.

Comments

1
$items = "";
foreach ($_SESSION["products"] as $cart_itm) {      
$items .= $cart_itm["code"] . " - " . $cart_itm["qty"] . " - "  . $cart_itm["price"] . "<br>" ;

}

echo $items;

Comments

0
$foo = '';
foreach ($loopable as $item) {      
$foo = $foo.'-'.$item;
}
echo $foo;

Make sure to init that variable before the for loop

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.