Tuesday, November 07, 2006

What is the difference between is_numeric() and ctype_digit() in PHP?

In PHP, there are two easy ways to determine whether a particular string is numerical is_numeric() and ctype_digit().
The difference is subtle, but important one. Which function you use depends on the condition for which you’re testing.
is_numeric tests whether the string in question is a number. ctype_digit(), on the other hand, tests whether the string in question contains all numeric characters.
Confused? Perhaps the code below will help.
$n = '1234.5';
var_dump(is_numeric($n)); // returns bool(true)
var_dump(ctype_digit($n)); // returns bool(false)
In the above example $n is a number. But see that decimal point? That’s not a numeric character, therefore ctype_digit($n) is false.

No comments: