如何在计算代码之前获取$total的值



我想显示一个在foreach循环中计算的变量内容。问题是我想在循环之前回显它。

<?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
    }
?>

我确实想在循环内回显它,但只在完成循环后回显一次。知道我该如何解决这个问题吗?我试过global $total但没有工作...

提前感谢!

一般 - 。您不能回显尚未计算的变量(PHP 中的同步)。

如果您在for-loop中所做的有关$total所做的所有事情都增加了 1,那么您实际上计算了数组中的元素数量,因此您可以执行以下操作:

echo count($pathList);

for-loop之前.文档在这里

更新:

如果$total在循环中受到影响(当您更新问题时),那么我相信最佳实践是先计算数组元素(不再执行任何代码),然后回显$total,然后循环原始数据并执行其余代码。

$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
}

这可能会以O(2*n)运行,但不会更糟

这是不可能的。行按它们在脚本中出现的顺序执行。

循环末尾的 $total 值等于 count($pathList) 的值

如果你在循环执行之前需要$pathList的最后一个迭代元素的值,那么它可以回显为

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