I just want to know the method to check a PHP variable for any non-numbers and if it also detects spaces between characters? Need to make sure nothing weird gets put into my form fields. Thanks in advance.
The is_numeric() function checks whether a variable is a number or a numeric string. This function returns true (1) if the variable is a number or a numeric string, otherwise it returns false/nothing.
PHP – How to check if String contains Number(s)?ctype_digit() function returns true if the string passed to it has digits for all of its characters, else it returns false.
Definition and UsageThe is_nan() function checks whether a value is 'not a number'. This function returns true (1) if the specified value is 'not-a-number', otherwise it returns false/nothing.
In JavaScript, there are two ways to check if a variable is a number : isNaN() – Stands for “is Not a Number”, if variable is not a number, it return true, else return false. typeof – If variable is a number, it will returns a string named “number”.
If you mean that you only want a value to contain digits then you can use ctype_digit()
.
You can use is_numeric()
:
if ( is_numeric($_POST['foo']) ) {
$foo = $_POST['foo'];
} else {
// Error
}
This will check that the value is numerical, so it may contain something else than digits:
12
-12
12.1
But this will ensure that the value is a valid number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With