Error while getting values from php foreach loop

The foreach loop I am using is generating same value multiple times even though those values are present only once in the main array
I am getting main array like below

                      Array
  (
    [0] => Array
    (
        [id] => 1
        [title] => Pizza
        [amount] => 100

    )
    [1] => Array
    (
        [id] => 2
        [title] => Burger
        [amount] => 50

    )
)

I am displaying values using foreach loop like below

            foreach($main_array as $k=>$v){
                $item_amount += $v['amount'];
                $item_title_and_amount .= $v['title'].':'.$v['amount'].',';              
                 }

but in the output I am getting values in the manner below

        Pizza:100,Burger:50,Pizza:100,Burger:50,Pizza:100,Burger:50,Pizza:100,Burger:50,  

but I want it to dislay like only once

Pizza:100,Burger:50

but Its not working like I need
What should I do to fix it ?

There must be something else going on. I tried this code:

<?php
echo "<pre>";
$x = array();
$x[] = array("id"=>1, "title"=>"Pizza", "amount"=>100);
$x[] = array("id"=>2, "title"=>"Burger", "amount"=>50);
print_r($x);
$item_amount = "";
$item_title_and_amount = "";
   foreach($x as $k=>$v){
                $item_amount += $v['amount'];
                $item_title_and_amount .= $v['title'].':'.$v['amount'].',';   
                 }
echo $item_title_and_amount;
echo "</pre>";
?>

and I get this output

Array
(
    [0] => Array
        (
            [id] => 1
            [title] => Pizza
            [amount] => 100
        )

    [1] => Array
        (
            [id] => 2
            [title] => Burger
            [amount] => 50
        )

)
Pizza:100,Burger:50,

which shows the two items, once each time.

You don’t show your output code, so it’s difficult to know whether it’s there, or somewhere else. A quick echo at the end of your loop would show you whether you’re building the strings correctly or not.

1 Like