Php 在foreach中每n个循环后调用一个函数?

Php 在foreach中每n个循环后调用一个函数?,php,Php,我的代码中有一个foreach循环,任务的进度取决于它。现在,我无法找到foreach循环中正在进行的循环。最终,我无法跟踪进度 有没有比包含一个递增变量并检查它是否跨越了n个循环更好的方法 简而言之:是否要改进以下功能 例如: <?php $counter = 1; $theN = 100; foreach( $allLoops as $thisLoop ) { /* The code to perform the "task" */ if( $count

我的代码中有一个foreach循环,任务的进度取决于它。现在,我无法找到foreach循环中正在进行的循环。最终,我无法跟踪进度

有没有比包含一个递增变量并检查它是否跨越了n个循环更好的方法

简而言之:是否要改进以下功能

例如:

<?php
$counter = 1;
$theN = 100;
foreach( $allLoops as $thisLoop ) {
    /*
    The code to perform the "task"
    */
    if( $counter%$theN == 0 ) {
        theFunction();
    }
    $counter++;
}

不,您需要保留一个计数器,否则无法使用foreach。有了常规的for循环,你已经有了一个计数器。所以你可以用这个

但我认为将变量与foreach循环一起使用是最简单的方法,这基本上就是您已经拥有的方法。:)(与只调用函数一次的其他答案相反)


你能举个例子吗?
$counter = 1;

foreach($array as $key => $value)
{
    if ($counter++ % 5 == 0)
    {
        // This code is executed every fith loop.
    }
}