在PHP中找出一个数字/变量是奇数还是偶数的最简单最基本的方法是什么? 这和mod有关吗?

我试过一些剧本,但是…谷歌目前没有发送。


当前回答

所有偶数除以2都得整数

$number = 4;
if(is_int($number/2))
{
   echo("Integer");
}
else
{
   echo("Not Integer");
}

其他回答

两个简单的位函数,返回0表示False,返回1表示True。

# is_odd: 1 for odd , 0 for even
odd = number & 1

# is_even: 1 for even , 0 for odd
even = number & 1 ^ 1

$number %2 = 1如果是奇数…所以不用用not even…

$number = 27;

if ($number % 2 == 1) {
  print "It's odd";
}

试试这个,

$number = 10;
 switch ($number%2)
 {
 case 0:
 echo "It's even";
 break;
 default:
 echo "It's odd";
 }
$before = microtime(true);

$n = 1000;  
$numbers = range(1,$n);

$cube_numbers = array_map('cube',$numbers);

function cube($n){      
    $msg ='even';       
    if($n%2 !=0){
        $msg = 'odd';
    }               
    return "The Number is $n is ".$msg;
}

foreach($cube_numbers as $cube){
    echo $cube . "<br/>";
}

$after = microtime(true);

echo $after-$before. 'seconds';
(bool)($number & 1)

or

(bool)(~ $number & 1)