繁体   English   中英

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)仍然可以工作(在您固定分配运算符之后),因为所有非空数组都被视为“真假”。

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

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

http://php.net/array_filter

 if(count($only_integers) == count($array))  {
     echo 'right';
 } else {
     echo 'wrong';
 }
  1. is_int()对于字符串"1"将返回false
    我看到您现在已编辑问题以使用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';
}
?>

尝试此代码,您将了解为什么您的代码不起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM