2014-09-05 68 views
-2

我是PHP的新手,並在其中取得一個類,我有一個任務只返回數組中的偶數。從php.net網站模數應該爲此工作,但它似乎沒有返回任何東西。這段代碼有什麼問題?PHP的模數foreach條件只顯示偶數的數組

<?php 
     // colors Array 
     $colors = array(
      0 => "Red", 
      1 => "Pink", 
      2 => "Blue", 
      3 => "Baby Blue", 
      4 => "Green", 
      5 => "Lime", 
      6 => "Black", 
      7 => "Grey", 
      8 => "Purple", 
      9 => "Violet" 
     ); 

     // Repeat Part 1 above, but only display the solid colors 
     krsort($colors); 
     // For Each item in array, Loop through the colors of the array and display the index number and color name. 
     foreach($colors as $key => $color){ 
      if($key % == 2) 
       echo "<p class='sub-heading'>Color: {$key}: is {$color}</p>"; 

     } // end forEach loop 
     ?> 
+1

嘗試'$鍵%2 == 0' 。 – bzeaman 2014-09-05 10:39:47

+0

謝謝,那個技巧 – jmccommas 2014-09-05 10:46:06

+0

只記得modulo是除法後的餘數,0是偶數1會是奇數等。 – Alex 2014-09-05 10:49:31

回答

1

使用模運算符來獲得期望的結果正確的方法:$key % 2 === 0

因此,例如for循環:

foreach($array as $key => $value){ 
    if($value % 2 === 0) { 
     // ... 
    } 
}