Recipe 2.2 Checking Whether a String Contains a Valid Number
2.2.1 Problem
You want to ensure that a string
contains a number. For example, you want to validate an age that the
user has typed into a form input field.
2.2.2 Solution
Use is_numeric( ):
if (is_numeric('five')) { /* false */ }
if (is_numeric(5)) { /* true */ }
if (is_numeric('5')) { /* true */ }
if (is_numeric(-5)) { /* true */ }
if (is_numeric('-5')) { /* true */ }
2.2.3 Discussion
Besides working on
numbers,
is_numeric( ) can also be applied to numeric
strings. The distinction here is that the integer
5 and the string 5 technically
aren't the same in PHP.
Helpfully, is_numeric( ) properly parses decimal
numbers, such as 5.1; however, numbers with
thousands separators, such as 5,100, cause
is_numeric( ) to return false.
To strip the thousands separators from your number before calling
is_numeric( ) use str_replace(
):
is_numeric(str_replace($number, ',', ''));
To check if your number is a specific
type, there are a variety of self-explanatorily named related
functions: is_bool( ) , is_float( ) (or
is_double( ) or is_real( );
they're all the same), and is_int(
) (or is_integer( ) or is_long(
)).
2.2.4 See Also
Documentation on is_numeric(
) at
http://www.php.net/is-numeric and
str_replace( ) at
http://www.php.net/str-replace.
|