Does A String In PHP Contain A Number?

24th December 2007 - 2 minutes read time

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:

  1. is_numeric('five') // returns false
  2. is_numeric(123); // returns true
  3. is_numeric('123'); // returns true
  4. is_numeric(-123); // returns true
  5. is_numeric('-123'); // returns true
  6. is_numeric('123.4'); // returns true
  7. 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.