How to check that a string is an int, but not a double, etc.?
How about using ctype_digit
?
From the manual:
<?php
$strings = array('1820.20', '10002', 'wsl!12');
foreach ($strings as $testcase) {
if (ctype_digit($testcase)) {
echo "The string $testcase consists of all digits.\n";
} else {
echo "The string $testcase does not consist of all digits.\n";
}
}
?>
The above example will output:
The string 1820.20 does not consist of all digits. The string 10002 consists of all digits. The string wsl!12 does not consist of all digits.
This will only work if your input is always a string:
$numeric_string = '42';
$integer = 42;
ctype_digit($numeric_string); // true
ctype_digit($integer); // false
If your input might be of type int
, then combine ctype_digit
with is_int
.
If you care about negative numbers, then you'll need to check the input for a preceding -
, and if so, call ctype_digit
on a substr
of the input string. Something like this would do it:
function my_is_int($input) {
if ($input[0] == '-') {
return ctype_digit(substr($input, 1));
}
return ctype_digit($input);
}
filter_var
should do it:
var_dump(filter_var('2', FILTER_VALIDATE_INT)); // 2
var_dump(filter_var('2.0', FILTER_VALIDATE_INT)); // false
var_dump(filter_var('2.1', FILTER_VALIDATE_INT)); // false
but
var_dump(filter_var(2, FILTER_VALIDATE_INT)); // 2
var_dump(filter_var(2.0, FILTER_VALIDATE_INT)); // 2
var_dump(filter_var(2.1, FILTER_VALIDATE_INT)); // false
If you just want Booleans as return values, wrap it into a function, e.g.
function validatesAsInt($number)
{
$number = filter_var($number, FILTER_VALIDATE_INT);
return ($number !== FALSE);
}