php - How to get the value of a $total before the code calculated?
829
I want to show a content of variable whom been calculate in aforeach
loop. The problem is that I want to echo it before the loop.
<?php
echo $total; // note this line I want to appear the total count of loop. the problem is it cannot appear because it is in the above of foreach loop. I want to appear it in this above before foreach loop.
$total = 0;
foreach($pathList as $item) {
$fileInfo = pathinfo($item);
if(preg_match(strtolower('/\b'.$_POST['song'].'\b/'), strtolower($filename))) {
$total = $total + 1; // the total count of foreach loop I want to appear in echo $total
}
// some code
}
?>
I do want to echo it inside the loop but only once after completed the loop.
Any idea how do I solve this problem? I triedglobal $total
but not working...
Thanks in advance!
Answer
Solution:
Generally - NO. You cannot echo variable that not been calculate yet (synchronization in PHP).
If all you do in the
for-loop
regarding$total
is increasing by 1 then you actually count the number of element in the array so you can just do:Before the
for-loop
. Documentation in hereUpdated:
If
$total
is affected in the loop (as you updated the question) then I believe best practice will be to counting array element first (without executing any more code), then echo the$total
, afterward, loop on the original data and execute the rest of your code.This may run at
O(2*n)
but its not worseAnswer
Solution:
It is not possible. Lines are executed in the order in which they appear in the script.
Answer
Solution:
The value of $total at the end of the loop is equal to the value of count($pathList)
If you need the value of the last iterated element of the $pathList before the execution of the loop, then it can be echoed as