2012-04-11 51 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 
     } 
    }