Check if given number is Even, Odd or Neither in PHP?

2.9k Views Asked by At

How can I get if a number is even or odd or neither (have decimal, like 1.5) with PHP? I know that there are operators like *, /, but they did not work.
Here's a try (of course it did not) (work that's just to find if it's a even number):

function even($n) {
    return (($n/2)*2 == $n);
}
echo even(1); // true (should be false)
echo even(2); // true
5

There are 5 best solutions below

0
On BEST ANSWER

It is pretty simple. modulo (%) is the operator you want, it determines if there would be a remainder if x is divided by y... for example (3 % 2 = 1) and (4 % 2 = 0). This has been asked before too - pretty common question - you really just need to see if your number, $n % 2 is equal to 0.

php test if number is odd or even

1
On

is_numeric returns true if the given variable is a number

is_int returns true if the given variable is an integer

The modulor operator % can be used to determine if an integer is even or odd:

$num % 2 == 0 // returns true if even, false if odd
0
On

Check if given number is integer first. And bitwise & to check if it is even or odd. Here is an example...

if (is_int($n)) {
    if ($n & 1) {
        echo 'Odd!';
    } else {
        echo 'Even!';
    }
} else {
    echo "Not a Integer!";
}

Hope this is helpful.

1
On

Use the modulo operator (%) to determine whether the integer is divisible by 2. You also need abs() to handle negative numbers, and is_int() to handle the fact that the modulo operator doesn't correctly handle floating point numbers. An example implementation follows:

function is_even($num) {
    return is_int($num) && abs($num % 2) == 0;
}
function is_odd($num) {
    return is_int($num) && abs($num % 2) == 1;
}
// this last one seems self-explanatory, but if you want it, here it is
function is_neither_even_nor_odd($num) {
    return !is_even($num) && !is_odd($num);
}

// Tests: The following should all output true:
var_dump(
    is_even(0),
    is_even(2),
    is_even(-6),
    is_even(51238238),
    is_odd(1),
    is_odd(-1),
    is_odd(57),
    is_neither_even_nor_odd(1.5),
    is_neither_even_nor_odd(2.5),
    is_neither_even_nor_odd(-0.5),
    is_neither_even_nor_odd(0.00000001)
    );

Here's a demo.

4
On

How about

function even($n) {
    if (!is_int($n)) {return 'n';}
    return !($n % 2);
}

even(1); // false;
even(2); // true;
even(1.5); // 'n'

The danger here is that 'n' will evaluate as false if used as a boolean. It might be better to return some specific constants instead of true or false. The OP didn't specify what the return values should be.