2016-09-22 6 views
0

この配列を考えてみましょう:モジュラスのevalの最初の発生を取得

$numbers = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]; 

どのようにループこの配列を通って、最初の番号と以下のevalが真である最後の番号を得ることができますか?

foreach($numbers as $number){ 
    if(($number % 2)==0){ 
     //This will execute for the numbers 2,4,6, etc... 
     //The first occurrence here will be 2 and the last will be 16 
     } 
} 

答えて

2

私があなたを得たならば、偶数の値の最小値と最大値のみを求めてください。 ヘルパー変数を作成すると、これを簡単に解決できます。

<?php 
$numbers = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]; 
$even = array(); 

foreach($numbers as $number){ 

    if(($number % 2) == 0){ 
     //This will execute for the numbers 2,4,6, etc... 
     //The first occurrence here will be 2 and the last will be 16 
     // Store only even values on the array to access it later using min() and max() functions 
     $even[] = $number; 

     } 
} 

print_r($even); 

echo min($even); // prints 2 
echo max($even); // prints 16 
?> 
0
function getNumber(Array $numbers) { 

    foreach($numbers as $number) { 
     if (!($number % 2)) { 
      return $number; 
     } 
    } 

} 

$numbers = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]; 
$first = getNumber($numbers); // 2 
$last = getNumber(array_reverse($numbers)); // 16 
0
$first = null; 
$temp = null; 

foreach($numbers as $number){ 
    if(($number % 2)==0){ 
     //This will execute for the numbers 2,4,6, etc... 
     //The first occurrence here will be 2 and the last will be 16 

     // 
     $temp = $number; 

     // Check if the first number has been assigned yet, if not set to $first 
     if ($first === null) { 
      $first = $number; 
     } 
    } 
} 

// Retrieve last valid value and set as last 
$last = $temp; 

+0

シェリフの答えは優れているトリックを行う必要があります。 –

0
$numbers = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]; 


foreach ($numbers as $number) { 
    if(0===($number%2)) 
    { 
     (!isset($first)) ? $first=$number : $last=$number; 
     $last = $number; 
    } 
} 
echo $first.'<br />'; 
echo $last.'<br />'; 
関連する問題