-2

I think it would be simple but I seem not to get it done. what I want to do is to display value I get from FOREACH loop on top of other echoed values.

function writeMsg($total) {
echo $total. "< This must display First";
}

foreach ($array as $value) {
   echo $value["Price"]."<br>";
   $total = $value["Total"];
}

writeMsg($total);

Note that I already echo the value inside the foreach, but what I want is to echo the variable I got from

$total = $value["Total"];

before

 echo $value["Price"]."<br>";

I hope you guys understand my issue!

Natalie Hedström
  • 2,607
  • 3
  • 25
  • 36

3 Answers3

2

You could use output buffering:

ob_start(); // everything echo'ed now is buffered
foreach ($array as $value){
    echo $value["Price"]."<br>";
    $total = $value["Total"];
}
$all_the_echoes = ob_get_clean(); // capture buffer to variable

writeMsg($total); // echoes the total
echo $all_the_echoes; // echoes the captured buffer

Note that there is probably a cleaner solution, but unless you update your question, it's guesswork to me what you are trying to achieve.

Gordon
  • 312,688
  • 75
  • 539
  • 559
0

i am not completely sure what are trying to get, but my guess is:

function writeMsg($total) {
echo $total. "< This must display First";
}
$total = 0;
$prices = array();

foreach ($array as $value){
    $prices [] = $value["Price"];
    $total += $value["Total"];
}

echo implode("<br>", $prices);
echo "<br>";
writeMsg($total);
backbone
  • 98
  • 1
  • 1
  • 8
0

I think what you want looks something like this. In the foreach loop you want to accumulate data and echo them out later. there you can choose what to echo first.

function writeMsg($total) {
    echo $total. "< This must display First";
}


$total = 0;
$prices = '';

foreach ($array as $value){
    // concatenate all prices into a single string. echo this later (after echo of totals)
    $prices .= $value["Price"]."<br>";

    // sum up total of all values
    $total += $value["Total"];
}

writeMsg($total);
echo $prices;
kscherrer
  • 5,486
  • 2
  • 19
  • 59