PHP: Checking if a variable contains only digits
For checking if a variable contains only digits, without the commas, periods, positive and negative signs, ctype_digit and preg_match are the functions you should use instead of is_numeric and is_int.
An array of numbers to verify, the first four should all evaulate to true and the last four should all evaluate to false.
$numbers = array( 987654321, 1234567890, "0987654321", "1234567890", -1, 2.2, 1e5, '1e3' );
bool ctype_digit(string $var), returns true if every character in the parameter is a decimal digit, false otherwise.
echo "cctype_digit \n"; foreach( $numbers as $n ) { if( ctype_digit($n) ) echo "true, digits only: $n \n"; else echo "false, NOT digits only: $n \n"; } echo "\n\n\n"; // cctype_digit // true, digits only: 987654321 // true, digits only: 1234567890 // true, digits only: 0987654321 // true, digits only: 1234567890 // false, NOT digits only: -1 // false, NOT digits only: 2.2 // false, NOT digits only: 100000 // false, NOT digits only: 1e3
int preg_match(string $pattern, string $var), returns 1 if the pattern matches the given string $var, 0 otherwise.
echo "preg_match \n"; foreach( $numbers as $n ) { if( preg_match('/^\d+$/',$n) ) echo "true, digits only: $n \n"; else echo "false, NOT digits only: $n \n"; } echo "\n\n\n"; // preg_match // true, digits only: 987654321 // true, digits only: 1234567890 // true, digits only: 0987654321 // true, digits only: 1234567890 // false, NOT digits only: -1 // false, NOT digits only: 2.2 // true, digits only: 100000 // false, NOT digits only: 1e3
bool is_numeric(mixed $var), returns true if the parameter $var is a number(including negative numbers, numbers with decimal places and numbers in scientific notations) or a numeric string, false otherwise.
echo "is_numeric \n"; foreach( $numbers as $n ) { if( is_numeric($n) ) echo "true, digits only: $n \n"; else echo "false, NOT digits only: $n \n"; } echo "\n\n\n"; // is_numeric // true, digits only: 987654321 // true, digits only: 1234567890 // true, digits only: 0987654321 // true, digits only: 1234567890 // true, digits only: -1 // true, digits only: 2.2 // true, digits only: 100000 // true, digits only: 1e3
bool is_int(mixed $var), returns ture if $var is an integer, false otherwise;
echo "is_int \n"; foreach( $numbers as $n ) { if( is_int($n) ) echo "true, digits only: $n \n"; else echo "false, NOT digits only: $n \n"; } echo "\n\n\n"; // is_int // true, digits only: 987654321 // true, digits only: 1234567890 // false, NOT digits only: 0987654321 // false, NOT digits only: 1234567890 // true, digits only: -1 // false, NOT digits only: 2.2 // false, NOT digits only: 100000 // false, NOT digits only: 1e3
Search within Codexpedia
Search the entire web