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
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