Kisaragi Kisaragi - 2 months ago 18
PHP Question

Getting the first occurrence of modulus eval

Consider this array:

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


How can I loop through this array and get the FIRST number and the LAST number where the eval below is true?

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

Answer

If I got you right you want the min and the max only of even values. Creating a helper variable should solve this easily.

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