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
$items = "";
foreach ($_SESSION["products"] as $cart_itm) {
$items .= $cart_itm["code"] . " - " . $cart_itm["qty"] . " - " . $cart_itm["price"] . "<br>" ;
}
echo $items;
$foo = '';
foreach ($loopable as $item) {
$foo = $foo.'-'.$item;
}
echo $foo;
Make sure to init that variable before the for loop
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);