简体   繁体   English

从阵列中获得最高偶数

[英]Getting highest even number out of an array

I need to get the greatest even number out of this array with a for-loop. 我需要通过for循环从这个数组中获得最大的偶数。 I know how to get the highest number from the loop, but it's not even. 我知道如何从循环中获得最高数字,但它甚至不是。

This is the code I have so far: 这是我到目前为止的代码:

<?php
// array aangemaakt
$aReeks = array(23, 245, 1, 2, 12, -10, 46, 6, 66, 9999, -55, 348, 56, 6, 66, 983); 
$resultaat = 0;

for ($i = 0; $i < count($aReeks); $i++) {
    if ($resultaat < $aReeks[$i])
          $resultaat = $aReeks[$i];
}

echo $resultaat;

?>
if($resultaat < $aReeks[$i] && $aReeks[$i] % 2 == 0)

除以2的模数为零 - >偶数

To find the highest odd number inside an array , you can use array_filter and max . 要查找array 最高的 奇数 ,可以使用array_filtermax

$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){...}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM