用于is_numeric()
检查变量是否为整数是一个坏主意。TRUE
例如,此功能将发送3.14
。这不是预期的行为
要正确执行此操作,您可以使用以下选项之一:
考虑到这个变量数组:
$variables = [
"TEST 0" => 0,
"TEST 1" => 42,
"TEST 2" => 4.2,
"TEST 3" => .42,
"TEST 4" => 42.,
"TEST 5" => "42",
"TEST 6" => "a42",
"TEST 7" => "42a",
"TEST 8" => 0x24,
"TEST 9" => 1337e0
];
第一个选项(FILTER_VALIDATE_INT 方式):
# Check if your variable is an integer
if( ! filter_var($variable, FILTER_VALIDATE_INT) ){
echo "Your variable is not an integer";
}
输出 :
TEST 0 : 0 (type:integer) is not an integer ✘
TEST 1 : 42 (type:integer) is an integer ✔
TEST 2 : 4.2 (type:double) is not an integer ✘
TEST 3 : 0.42 (type:double) is not an integer ✘
TEST 4 : 42 (type:double) is an integer ✔
TEST 5 : 42 (type:string) is an integer ✔
TEST 6 : a42 (type:string) is not an integer ✘
TEST 7 : 42a (type:string) is not an integer ✘
TEST 8 : 36 (type:integer) is an integer ✔
TEST 9 : 1337 (type:double) is an integer ✔
第二种选择(铸造比较方式):
# Check if your variable is an integer
if ( strval($variable) != strval(intval($variable)) ) {
echo "Your variable is not an integer";
}
输出 :
TEST 0 : 0 (type:integer) is an integer ✔
TEST 1 : 42 (type:integer) is an integer ✔
TEST 2 : 4.2 (type:double) is not an integer ✘
TEST 3 : 0.42 (type:double) is not an integer ✘
TEST 4 : 42 (type:double) is an integer ✔
TEST 5 : 42 (type:string) is an integer ✔
TEST 6 : a42 (type:string) is not an integer ✘
TEST 7 : 42a (type:string) is not an integer ✘
TEST 8 : 36 (type:integer) is an integer ✔
TEST 9 : 1337 (type:double) is an integer ✔
第三个选项(CTYPE_DIGIT方式):
# Check if your variable is an integer
if( ! ctype_digit(strval($variable)) ){
echo "Your variable is not an integer";
}
输出 :
TEST 0 : 0 (type:integer) is an integer ✔
TEST 1 : 42 (type:integer) is an integer ✔
TEST 2 : 4.2 (type:double) is not an integer ✘
TEST 3 : 0.42 (type:double) is not an integer ✘
TEST 4 : 42 (type:double) is an integer ✔
TEST 5 : 42 (type:string) is an integer ✔
TEST 6 : a42 (type:string) is not an integer ✘
TEST 7 : 42a (type:string) is not an integer ✘
TEST 8 : 36 (type:integer) is an integer ✔
TEST 9 : 1337 (type:double) is an integer ✔
第四个选项(REGEX方式):
# Check if your variable is an integer
if( ! preg_match('/^\d+$/', $variable) ){
echo "Your variable is not an integer";
}
输出 :
TEST 0 : 0 (type:integer) is an integer ✔
TEST 1 : 42 (type:integer) is an integer ✔
TEST 2 : 4.2 (type:double) is not an integer ✘
TEST 3 : 0.42 (type:double) is not an integer ✘
TEST 4 : 42 (type:double) is an integer ✔
TEST 5 : 42 (type:string) is an integer ✔
TEST 6 : a42 (type:string) is not an integer ✘
TEST 7 : 42a (type:string) is not an integer ✘
TEST 8 : 36 (type:integer) is an integer ✔
TEST 9 : 1337 (type:double) is an integer ✔