检查数组是否为数字的 PHP 代码不起作用


PHP code to check if array is numeric is not working

我有以下PHP:

 <?php
 $array = array("1","2","3");
 $only_integers === array_filter($array,'is_numeric'); // true
 if($only_integers == TRUE)
 {
 echo 'right';
 }
 ?>

出于某种原因,它总是不返回任何内容。我不知道我做错了什么。

谢谢

is_int检查变量的实际类型,这在您的情况下string。对数值使用 is_numeric,而不考虑变量类型。

请注意,以下值都被视为"数字":

"1"
1 
1.5
"1.5"
"0xf"
"1e4"
即任何浮点数、整数或字符串,这些浮点数或

字符串将是浮点数或整数的有效表示。

编辑:另外,您可能误解了array_filter,它不返回true或false,而是一个新数组,其中包含回调函数返回true的所有值。 尽管如此,if($only_integers)仍然有效(在您修复了赋值运算符之后(,因为所有非空数组都被认为是"true-ish"。

编辑 2:正如@SDC指出的,如果您只想允许十进制格式的整数,则应使用 ctype_digit

您必须将原始数组的长度与过滤数组的长度进行比较。array_filter 函数返回一个数组,其值与筛选器设置为 true 匹配。

http://php.net/array_filter

 if(count($only_integers) == count($array))  {
     echo 'right';
 } else {
     echo 'wrong';
 }
  1. is_int() 将返回 false 表示"1",因为它是一个字符串.
    我看到您现在已经编辑了问题以改用is_numeric();这也可能是个坏主意,因为它会为十六进制和指数值返回 true,您可能不想要(例如is_numeric("dead")将返回 true(.
    我建议改用ctype_digit()

  2. 三等在这里被滥用了。它用于比较,而不是分配,因此永远不会设置$only_integers。使用单等号设置$only_integers

  3. array_filter() 不返回 true/false 值;它返回数组,并删除过滤后的值。这意味着后续检查$only_integers是否为 true将不起作用。

  4. $only_integers == TRUE .这没关系,但您可能应该在这里使用三等。但是,当然,我们已经知道$only_integers不会是truefalse,它将是一个数组,所以实际上我们需要检查它是否有任何元素。 count()会在这里解决问题。

这是您的代码的样子,考虑到所有这些...

 $array = array("1","2","3");
 $only_integers = array_filter($array,'ctype_digit'); // true
 if(count($only_integers) > 0)
 {
     echo 'right';
 }

更改=== =它用于比较而不是初始化变量

<?php
 $array = array(1,2,3);
 $only_integers = array_filter($array,'is_int'); // true
 if($only_integers == TRUE)
 {
 echo 'right';
 }
?>

您是否尝试在发布之前运行代码?我有这个错误:

Notice: Undefined variable: only_integers in ~/php/test.php on line 4
Notice: Undefined variable: only_integers in ~/php/test.php on line 6

===更改为=可立即解决问题。你最好学习如何使用phplint和其他工具来避免这样的错别字错误。

<?php
$test1 = "1";
if (is_int($test1) == TRUE) {
    echo '$test1 is an integer';
}
$test2 = 1;
if (is_int($test2) == TRUE) {
    echo '$test2 is an integer';
}
?>

试试这段代码,你就会明白为什么你的代码不起作用。