Does A String In PHP Contain A Number?

The is_numeric() function in PHP can be used to see if a number contained in a string is numeric. The function returns true is the variable can be parsed into a string, otherwise it returns false. Here are some examples:

is_numeric('five')  // returns false
is_numeric(123); // returns true
is_numeric('123'); //  returns true
is_numeric(-123); //  returns true
is_numeric('-123'); //  returns true
is_numeric('123.4'); //  returns true
is_numeric('1,234'); //  returns false

Notice that if your number has a thousand separator in it the function will return false. In this case you need to use the str_replace() function to strip out the commas before passing the value into is_numeric(0).

is_numeric(str_replace(',' ,'' ,'1,234')); // returns true

Remember that by default all GET and POST variables will be passed to PHP as strings so this function is useful when checking form input as it can verify that a value is a number before you go on to check the value of that number.

PHP also has a variety of other functions to allow you to check that a variable is a number of a specific type. These are is_bool(), is_float() (also known as is_double() or is_real(), is_int() (also known as is_integer()), and is_long().

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
1 + 4 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.