Getting highest even number out of an array

前端 未结 2 1621
生来不讨喜
生来不讨喜 2021-01-21 15:50

I need to get the greatest even number out of this array with a for-loop. I know how to get the highest number from the loop, but it\'s not even.

This is the code I have

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-21 16:21

    To find the highest odd number inside an array, you can use array_filter and max.

    $aReeks = array(23,245,1,2,12,-10,46,6,66,9999,-55,348,56,6,66,983); 
    echo(max(array_filter($aReeks, function($var){return(!($var & 1));})));
    //348
    

    If you just need to find if a number is even or odd, you can use:

    //if Even Number
    $number = "222";
    if(!($number & 1)){...}
    
    //if Odd Number
    $number = "221";
    if($number & 1){...}
    

提交回复
热议问题