繁体   English   中英

如何在执行计算该值的代码之前回显变量的值?

[英]How do I echo the value of a variable before the code which calculates that value has been executed?

我想显示在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];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM