2012-04-11 53 views
2

如何在foreach中每5(例如)循环做些事情?步入里面foreach

我是补充$i++如何检查通过步骤?

+3

与模运算符%...($ I%5)== 1 ... – 2012-04-11 21:41:35

+2

使用模http://php.net/manual/en/language.operators.arithmetic。 PHP的 – Drewdin 2012-04-11 21:44:23

+0

可能重复[PHP的foreach迭代两次而不是一次](http://stackoverflow.com/questions/10072015/php-foreach-iterate-twice-instead-of-once) – GordonM 2012-04-11 22:01:28

回答

7

使用模数来确定偏移量。

$i = 0; 

foreach ($array as $a) { 
    $i++; 
    if ($i % 5 == 0) { 
     // your code for every 5th item 
    } 

    // your inside loop code 
} 
+1

或更好的是,不要使用模运算符。在5开始'$ i'; 'if( - $ i == 0){$ i = 5; //做其他事情' – 2012-04-11 21:51:13

+0

什么更快?模数在foreach中OR循环for? – skywind 2012-04-11 21:59:48

+1

如果你想在每个记录上做其他事情,那么用模数进行foreach。但是如果你只想处理Justin Niessner发布的第一个记录使用答案 - 第一个答案。 – castor 2012-04-11 22:19:44

6

除非您在每次迭代中单独做某事,否则不要。

for循环使用,并通过5每次递增计数器:

$collectionLength = count($collection); 

for($i = 0; $i < $collectionLength; i+=5) 
{ 
    // Do something 
} 

否则,你可以使用模运算符来确定,如果你是在第五次迭代的一个:

if(($i + 1) % 5 == 0) // assuming i starts at 0 
{ 
    // Do something special this time 
} 
+1

'count'每循环迭代一般坏主意 – hamczu 2012-04-11 21:48:51

+0

在第一个例子中,这应该是for循环中的'$ i + = 5'。 – svandragt 2014-03-03 09:48:27

1
for($i = 0; $i < $items; $i++){ 
    //for every 5th item, assuming i starts at 0 (skip) 
     if($i % 5 == 0 && $i != 0){ 
      //execute your code 
     } 
    }