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);
Written by Christopher W. Jones
Related protips
1 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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Php
Authors
Related Tags
#php
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#