Title: PHP is_int() and is_numeric()
Slug: php-is-int-and-is-numeric
Date: 2010-06-20 10:05:00
Author: Kartones
Lang: en
Tags: Development, PHP, Troubleshooting
Description: A discussion on PHP's is_int() and is_numeric() functions, highlighting the importance of proper variable handling in untyped languages like PHP.

 <p>When coding with PHP, the first requisite is a proper handling of variables, as they are not typed. We can think that the built-in <font face="Courier New">is_int()</font> function will work correctly to detect integer values inside a variable...</p> <p>Try this:</p> <p><font face="Courier New">$param = '1'; <br>echo is_int($param);</font></p> <p>It will return false, because it checks that <b>the type of the variable is an integer</b>... not that the variable's value can be interpreted as an integer ;)</p> <p>In order to properly test for numeric values, you have to always use <font face="Courier New">is_numeric()</font> (<a href="http://es.php.net/manual/en/function.is-numeric.php">documentation</a>), and then one of the following options:</p> <p>a) Do a cast (this works ok to detect floats, but will still fail with integers):</p> <p><font face="Courier New">$param = '12.5'; <br>echo is_float((float)$param);</font></p> <p>b) Create a regular expression to check numeric formats.</p> <p> </p> <p>Once again, the problem of untyped languages rises up. With a correctly typed language this wouldn't happen. <br>And with an untyped one, I wonder why leaving so many misleading functions instead of deprecating them in favor of correctly working ones...</p>