/**
* Check if a number is a counting number by checking if it
* is an integer primitive type, or if the string represents
* an integer as a string
*/
function is_int_val($data) {
if (is_int($data) === true) return true;
if (is_string($data) === true && is_numeric($data) === true) {
return (strpos($data, '.') === false);
}
}
<?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 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.
intval(array('foo', 'bar')) //returns 1 ?!?
intval("2dog") //returns 2 even though the value is definitely not an integer
intval("dog2") //also returns 2
1 - Valid integer.
+1 - Not a valid integer.
-1 - Valid integer.
01 - Not a valid integer.
1.0 - Not a valid integer.
.0 - Not a valid integer.
1.123 - Not a valid integer.
a123 - Not a valid integer.
0x101010 - Not a valid integer.
1 - Valid integer.
-1 - Valid integer.
1 - Valid integer.
1 - Valid integer.
0 - Valid integer.
1.123 - Not a valid integer.
1052688 - Valid integer.
$numbersToCheck = array("a", "-1", "1", "1.0", "1.2");
foreach ($numbersToCheck as $var) {
echo $var . " is integer? ";var_dump((is_numeric($var) && !is_double(1*$var)));
echo $var . " is a positive integer? ";var_dump((is_numeric($var) && !is_double(1*$var)) && ($var >= 0));
}
产出:
a is integer? bool(false)
a is a positive integer? bool(false)
-1 is integer? bool(true)
-1 is a positive integer? bool(false)
1 is integer? bool(true)
1 is a positive integer? bool(true)
1.0 is integer? bool(false)
1.0 is a positive integer? bool(false)
1.2 is integer? bool(false)
1.2 is a positive integer? bool(false)
并不是每个人都希望这样,这可能是处理用户输入的一种情况。Filter _ var 在这方面还不错,对于 PHP 新手来说,在大多数情况下是相当安全的。
对于用户输入,长度检查、 ctype _ data 和转换后的值检查(它在一个范围内)也是相当可靠的。更复杂的方案可能需要修剪或正则表达式。
这方面很多答案的问题在于,尽管问题很模糊,但答案不应该是模糊的。如果你打算提出一个解决方案,你应该能够准确地解释它将会和不会期望什么。没有这个,就不知道答案是否与问题相匹配或者是否安全。PHP 手册并不总是有帮助,因为它没有解释它提供的每个相关方法的所有警告。诸如 ctype _ digital 和 is _ int 之类的东西是非常可靠的,并且很容易预测,但是关于 is _ numeric、 filter _ var 和 jugging (+ $var)或 cast (intval/floatval)的细节文档很少。