开发者

Call a function after every n loops in foreach?

There's a foreach loop in my code, on which the progress of a task depends. Right now, there's no way I could find which loop is ongoing in the foreach loop. Ultimately, I cannot track the progress.

Is there any better way than including an incrementing variable and checking if it has crossed n loops?

In short: Anyway to improve the following function?

Example:开发者_高级运维

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


Nope, you'll need to keep a counter, or you cannot use foreach. With a regular for loop you got a counter already. So you could use that.

But I think using a variable together with the foreach loop is the easiest way, which is essentially what you already have. :) (In contrast to the other answers that will call the function only once).

$counter = 1;

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜