Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if PHP variable contains non-numbers?

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.

like image 974
user701510 Avatar asked Jun 09 '11 08:06

user701510


People also ask

How do you check if a variable is number or not in PHP?

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.

How do I check if a string contains numbers in PHP?

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.

Is not a number in PHP?

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.

How do you check if a variable contains a number?

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”.


2 Answers

If you mean that you only want a value to contain digits then you can use ctype_digit().

like image 59
Marty Avatar answered Oct 16 '22 12:10

Marty


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.

like image 30
Matthieu Napoli Avatar answered Oct 16 '22 12:10

Matthieu Napoli