3

I have an array like this.

Array ( 
       [1] => Array ( 
                     [Stock Code] => 1Y 1111 
                     [Price] => 20 
                     [Quantity] => 10 
                     [Amount] => 200 
                    ) 

       [2] => Array ( 
                     [Stock Code] => 0300058 
                     [Price] => 30 
                     [Quantity] => 2 
                     [Amount] => 60 
                    ) 
      )

And here my code for retrieving the value from the array using foreach loop.

<?php
  $cartOutput = "";
  $i=0;
  foreach($_SESSION['cart_array'] as $each_item){
    $i++;
        $cartOutput = "Stock Code: ".$each_item['Stock Code']."<br/>";
        $cartOutput = "Price: ".$each_item['Price']."<br/>";
        $cartOutput = "Quantity: ".$each_item['Quantity']."<br/>";
        $cartOutput = "Amount: ".$each_item['Amount']."<br/>";
  }
?>

Here is where I display the result in HTML

<div style="height:500px;">
<?php echo $cartOutput; ?>
</div>

The output is:

Amount: 60

But I expected result is display all the value of the array.

2 Answers 2

5

You are overwriting the variable in each iteration.Instead of that try to appened the value to the variable.Try like this

$cartOutput = "";
  $i=0;
  foreach($_SESSION['cart_array'] as $each_item){
    $i++;
        $cartOutput .= "Stock Code: ".$each_item['Stock Code']."<br/>";
        $cartOutput .= "Price: ".$each_item['Price']."<br/>";
        $cartOutput .= "Quantity: ".$each_item['Quantity']."<br/>";
        $cartOutput .= "Amount: ".$each_item['Amount']."<br/>";
  }
Sign up to request clarification or add additional context in comments.

Comments

1

In your foreach loop you should have

$cartOutput .= 

instead of just an =

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.