find even or odd number without modulo operator in php
I am having problem to find even or odd numbers without modulo sign. so that i cant prepare my code.
find even or odd number without modulo operator in php
I am having problem to find even or odd numbers without modulo sign. so that i cant prepare my code.
You could always use subtstr()
and a conditional that checks whether the last digit is 1
, 3
, 5
, 7
or 9
. This can be simplified with in_array()
:
$number = 12345;
$last = substr($number, -1);
if (in_array($last, array(1, 3, 5, 7, 9))) {
echo "odd";
}
else {
echo "even";
}
And shrunk with a ternary:
echo in_array($last, array(1, 3, 5, 7, 9)) ? "odd" : "even";
This can be seen working here.