◄ Back to BLOG INDEX

PHP: Optimized version of is_numeric(), is_integer()

Published May 25, 2014 21:05pm

Here's a small tip about how to optimize the performance of the is_numeric() and is_integer() functions by not using them at all.

For a given variable, $x = '1234', if you want to know if it is a number, the following code is 3 to 4 times faster than using the above functions.

if ($x == '0'.$x) { ... }

By simply prepending a string zero onto the front and then doing an equality check, you can immediately differentiate between numbers and non-numbers. This works because when a non-numeric string is evaluated as a number in PHP, it actually gets converted to the integer 0 (zero). But by prepending a string zero, we get an equality for numeric strings but an inequality for non-numeric strings. 

Give it a try yourself.

comments powered by Disqus