Placing data that is generated on bottom of page to top

I have a page with a few foreach loops in the middle of the page. In these foreach i do a sum of some vars to at the end of the foreachloop this $var has data.

Now i want to show this data on the top of my page before the foreach wich means if I dump the var it is false or not set…

Now i would like to know what the best way is to approach such a issue?

I could do the same foreach twice also at the top to get the data but what is best practice for these kinds of problems ?

just to give a example

$sum = false;
echo "<center>Sum: {$sum}</center>";

$sum = 0
foreach ($a as $b) {
$sum += $b
}

I understand that the var is false because the loop did not happen, but for design, i want to show this at first.. so how do i do this, javascrip?

Answer

One popular method is to manipulate your variables before you begin to process the actual output. To use your example, yes you would likely run the foreach once when processing the data, then again later on to display it.

For your specific example it may not be an obvious the benefit, but once you start working on larger pages that include more data it becomes a lot simpler to split the logic and display.

Process the data

<?php

$sum = 0;
foreach ($a as $b) {
  $sum += $b;
}

?>

Display it

<center>Total record(s): <?=$sum?></center>

<?php foreach($a as $b) { ?>

<p>Value: <?=$b?></p>

<?php } ?>

Note: the shorthand syntax of <?=$var?> means <?php echo $var; ?>, and is only on by default from PHP 5.4 onwards.

Edit to show an alternative

If you really only want to loop once, and are happy mixing your logic and display, you can build the HTML output that would ordinarily be inside your loop, as you calculate the sum.

<?php

$valuesHtml = "";
$sum = 0;
foreach ($a as $b) {
  $sum += $b;
  $valuesHtml .= "<p>Value: {$b}</p>";
}

?>

<center>Total record(s): <?=$sum?></center>

<?=$valuesHtml?>

Leave a Reply

Your email address will not be published. Required fields are marked *