首次出现模数eval

时间:2016-09-22 19:37:01

标签: php

考虑这个数组:

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

如何循环遍历此数组并获取下面的eval为真的FIRST数字和最后一个数字?

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
       }
}

4 个答案:

答案 0 :(得分: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
?>

答案 1 :(得分: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

答案 2 :(得分: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;

应该做的伎俩

答案 3 :(得分: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 />';