PHP判断奇数偶数的两个方法

一. 数字跟2取模如果为0则为偶数,否则为奇数

函数示例:

<?php 
function is_odd($num)
{
		if ($num % 2 == 0) {
				return false;
		} else {
				return true;
		}
}

if (is_odd($a)) {
echo $a.' is odd';
} else {
		echo $a.' is even';
}

if (is_odd(4)) {
		echo '4 is odd';
} else {
		echo '4 is even';
}

结果:

3 is odd
4 is even

二. 通过与运算

函数示例:

<?php 
function is_odd($num)
{
		return ($num & 1);
}

function is_even($num)
{
		return (!($num & 1));
}

$a = 3;
if (is_odd($a)) {
		echo $a.' is odd';
} else {
		echo $a.' is even';
}

if (is_even(4)) {
		echo '4 is even';
} else {
		echo '4 is odd';
}

结果:

3 is odd
4 is evenven