1

我有以下 PHP:

 <?php

 $array = array("1","2","3");
 $only_integers === array_filter($array,'is_numeric'); // true

 if($only_integers == TRUE)
 {
 echo 'right';
 }

 ?>

由于某种原因,它总是什么都不返回。我不知道我做错了什么。

谢谢

4

6 回答 6

2

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如果您只想允许十进制格式的整数,则应该使用。

于 2013-02-15T15:36:07.527 回答
2

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

http://php.net/array_filter

 if(count($only_integers) == count($array))  {
     echo 'right';
 } else {
     echo 'wrong';
 }
于 2013-02-15T15:43:54.133 回答
1
  1. is_int()将返回false"1"因为它是一个字符串。
    我看到你现在已经编辑了这个问题来is_numeric()代替使用;这也可能是一个坏主意,因为它将返回true您可能不想要的十六进制和指数值(例如is_numeric("dead")将返回 true)。
    我建议ctype_digit()改用。

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

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

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

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

 $array = array("1","2","3");
 $only_integers = array_filter($array,'ctype_digit'); // true

 if(count($only_integers) > 0)
 {
     echo 'right';
 }
于 2013-02-15T15:52:01.640 回答
0

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

<?php

 $array = array(1,2,3);
 $only_integers = array_filter($array,'is_int'); // true

 if($only_integers == TRUE)
 {
 echo 'right';
 }

?>
于 2013-02-15T15:40:08.357 回答
0

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

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 和其他工具来避免这样的拼写错误。

于 2013-02-15T15:47:51.320 回答
-1
<?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';
}
?>

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

于 2013-02-15T15:39:01.583 回答