How to check if a PHP variable contains non numbers?

I just want to know a method for checking a PHP variable for any non-numbers, and if it also detects spaces between characters? You need to make sure that nothing strange is added to the form fields. Thanks in advance.

+12
variables string php forms
source share
9 answers

If you mean that you want the value to contain only numbers, you can use ctype_digit() .

+17
source share

You can use is_numeric() :

 if ( is_numeric($_POST['foo']) ) { $foo = $_POST['foo']; } else { // Error } 

This will verify that the value is numeric, so it may contain something other than numbers:

 12 -12 12.1 

But this ensures that the value is a real number .

+16
source share

You can use ctype_digit

eg:

 if (!ctype_digit($myString)) { echo "Contains non-numbers."; } 
+14
source share

This will return true if there are no numbers in the string. It detects letters, spaces, tabs, newlines, regardless of number.

 preg_match('#[^0-9]#',$variable) 
+8
source share

This will check if the input value is numeric or not. Hope this helps

 if(!preg_match('#[^0-9]#',$value)) { echo "Value is numeric"; } else { echo "Value not numeric"; } 
+2
source share

PHP has an is_numeric () function, which may be what you are looking for.

+1
source share

Insert and compare:

 function string_contain_number($val) { return ($val + 0 == $val) ? true : false; } 
+1
source share
 if(!ctype_digit($string)) echo 'The string contains some non-digit' 
+1
source share

Assuming that you only want (and only) real integers, and you don't want users to mess up your data and database with hexadecimal or binary or any other form of numbers, you can always use this method:

 if(((string) (int) $stringVariable) === $stringVariable) { // Thats a valid integer :p } else { // you are out of luck :( } 

The trick is simple. It passes a variable of type string to an integer type, and then returns it to a string. Super fast, super simple.

For testing, I prepared a test:

 '1337' is pure integer. '0x539' is not. '02471' is not. '0000343' is not. '0b10100111001' is not. '1337e0' is not. 'not numeric' is not. 'not numeric 23' is not. '9.1' is not. '+655' is not. '-586' is pure integer. 

The only place this method crashes is negative numbers, so you need to check that next to it (use ((string) (int) $stringVariable) === $stringVariable && $stringVariable[0] !== "-" ).

Now I thought the preg_match method is the best. but in any project that concerns users, speed is an important factor. so I prepared a test test, doing it 500,000 times higher than the test, and the results were amazing:

My own invented method only took:
6.4700090885162
seconds to complete compared to preg_match , which took:
77.020107984543 seconds to complete this test!

0
source share

All Articles