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!

648

Answer

Solution:

Generally - NO. You cannot echo variable that not been calculate yet (synchronization in PHP).

If all you do in thefor-loop regarding$total is increasing by 1 then you actually count the number of element in the array so you can just do:

echo count($pathList);

Before thefor-loop. Documentation in here

Updated:

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.

$total = 0;
foreach($pathList as $item) {
   $fileInfo = pathinfo($item);
   if(preg_match(strtolower('/\b'.$_POST['song'].'\b/'), strtolower($filename))) // or what ever condition you have to check for total
       $total = $total + 1;
}
echo count($total); // give you the count you need
foreach($pathList as $item) {
    // exec the rest of your code
}

This may run atO(2*n) but its not worse

234

Answer

Solution:

It is not possible. Lines are executed in the order in which they appear in the script.

256

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

echo $pathList[count($pathList)-1];

People are also looking for solutions to the problem: php - Two where in one query

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.