使用
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 integerif ( filter_var($variable, FILTER_VALIDATE_INT) === false ) { 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 ✔
第二种选择(比较方式):
# Check if your variable is an integerif ( 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 integerif ( ! 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 integerif ( ! 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 ✔



