Last Updated: February 25, 2016
·
213
· jonesch

Always Return An Even Number

I needed a quick snippet to always return an even number, so this is what I came up with. Enjoy!

$num = (round((count($orig_num) / 2), 0, PHP_ROUND_HALF_EVEN) * 2);

1 Response
Add your response

I had to remove the count() before it worked. Also why don't you do a bitwise check, if the first bit is 1, we know it's an odd number:

// Add or substract 1 if it's odd
echo $num & 1 ? $num + 1 : $num;

For more information about bitwise operators check:
http://php.net/manual/en/language.operators.bitwise.php

Also note that the rounding seems a bit unpredictable, both 12345 and 12343 returned 12344 in your case.

over 1 year ago ·