PHP equivalent of JavaScript's parseInt function?

Lucas picture Lucas · Sep 29, 2012 · Viewed 61k times · Source

Possible Duplicate:
Check if a variable is a natural number

Just came across where I need to sanitize an input and remove all non-digit characters with PHP. Thought of making a function myself, but just first wanted to check up on the possible built-in functions, so I won't have to spend extra time reinventing the wheel.

Answer

Spudley picture Spudley · Sep 29, 2012

There isn't a direct equivalent to pareseInt() in PHP because PHP doesn't have a NaN data type. parseInt() will produce NaN if the value can't be parsed.

In addition, parseInt() has the radix parameter, which none of the PHP options give you.

But that said, if all you want to do is turn a string into an integer, then there are several options:

$int = (int)$string;

$int = intval($string);

$int = settype($string,'integer');

Those three will all work in much the same way. There may be some edge cases where intval() differs from the other two, but in general, they will turn a string into an int. In the absence of NaN, they all output 0 (zero) if the string is non numeric and can't be parsed. But this should be sufficient for most DB sanitation purposes.

If you really want a the NaN on error, the closest you'll get is null. You can get this using filter_var():

$value = filter_var(FALSE, FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);

If you just want to check that the string is numeric, the is_numeric() function can do that:

$bool = is_numeric($string);

However, it returns true for decimals and also for scientific notation, so may not be perfect for most situations. A better option is ctype_digit() which returns true if the string is made up only of digits:

$bool = ctype_digit($string);

If non e of this suits, there is always the regex option, using preg_match() or preg_replace(), but these are definitely overkill for this kind of scenario.