2013-06-24 113 views
1

當在foreach循環中滿足特定條件時是否可以再次運行當前索引?在下面發佈一個例子。在foreach循環中再次運行當前索引

$array = array('this', 'is', 'my', 'array'); 
$bool = false; 
foreach($array as $value){ 
    echo $value.' '; 
    if($value == 'my' && !$bool){ 
     // Rerun the 'my' index again 
     $bool = true; 
    } 
} 

希望的輸出:這是我的我的數組

+2

基本問題**爲什麼**? – Robert

回答

3

即使它可以是 p (通過prev或其他一些黑客),用這種方式編寫的代碼很難理解(即使在幾年內你自己也是如此)。對於程序員來說,foreach構造(乍看之下)看起來像是對數組中所有元素的簡單迭代,而不會來回跳動。

還要注意的是prev一個foreach內可以在一個PHP版本的工作,但在其他版本失敗! PHP docs say

作爲的foreach依賴於內部數組指針環路內改變,可能導致意外行爲

我會建議使用在你情況下while迴路(使用索引或each - prev - next功能)。 while構造是程序員的即時信號,其迭代邏輯比數組元素上的順序迭代更復雜。

$array = array('this', 'is', 'my', 'array'); 
$bool = false; 

while (list($key, $value) = each($array)) 
{ 
    echo $value.' '; 
    if($value == 'my' && !$bool) 
    { 
    // Rerun the 'my' index again 
    $bool = true; 
    prev($array); 
    } 
} 
+0

太棒了,謝謝! –

1

另一變型:

<?php 
$array = array('this', 'is', 'my', 'array'); 
$bool = false; 

foreach ($array as $value) { 
    do { 
     echo $value.' '; 

     if($value == 'my' && !$bool){ 
      // Rerun the 'my' index again 
      $bool = true; 
     } else { 
      $bool = false; 
     } 
    } while ($bool); 
} 

輸出(also see here):

this is my my array