为什么in_array不能在PHP中使用循环创建的数组上工作?

时间:2016-01-06 04:26:02

标签: php arrays

为什么in_array无法在从循环php创建的数组上工作?

以下代码显示Match found

<?php
for ($i = 0; $i < 10; ++$i) {
    $people[] = $i;
}    
if (in_array('test', $people))
  {
  echo "Match found";
  }
else
  {
  echo "Match not found";
  }
?>

以下代码显示Match not found

<?php
$people = array("0","1","2","3","4","5","6","7","8","9");
if (in_array('test', $people))
  {
  echo "Match found";
  }
else
  {
  echo "Match not found";
  }
?>

如何解决显示Match not found

的第一个代码

3 个答案:

答案 0 :(得分:7)

因为在你的第一个数组中你有整数,并且默认情况下debug in eclipse执行in_array(),它只考虑了non-strict type comparison。所以它会用你的针做一个静音强制转换为整数,结果为0,它会在数组中找到它。

要避免此错误,只需将init作为第三个参数传递给(defn connect! [] ;; Tries to get the Mongo URI from the environment variable (reset! db (-> (:database-url env) mg/connect-via-uri :db))) ,以便它执行limited amount of type pairs,例如

TRUE

答案 1 :(得分:2)

您只需更改

$people[] = $i; ---by--> $people[] = "$i";

然后你比较字符串

<?php

for ($i = 0; $i < 10; ++$i) {
    $people[] = "$i";

}   

if (in_array('test', $people))
  {
  echo "Match found";
  }
else
  {
  echo "Match not found";
  }
?>

答案 2 :(得分:2)

你已经得到了答案,告诉你如何解决这个问题。让我添加一个更技术性的答案为什么会发生这种情况......

这种行为植根于ZEND_API int compare_function(..)特有的作用方式 在没有$ strict = in_array(needle, haystack, strict)的情况下调用function is usedcomparegit diff-tree needle,其中包含haystack中的每个元素,直到找到匹配为止。
你的针是一个字符串,大海捞针中的元素是整数 让我们看一下({缩写)compare_function()

while(1) {
    switch (TYPE_PAIR(Z_TYPE_P(op1), Z_TYPE_P(op2))) {
        case TYPE_PAIR(IS_LONG, IS_LONG):
            ZVAL_LONG(result, Z_LVAL_P(op1)>Z_LVAL_P(op2)?1:(Z_LVAL_P(op1)<Z_LVAL_P(op2)?-1:0));
                return SUCCESS;
        [...more CASEs that don't apply on the first iteration of the while-loop...]
        default:
          [...some if-elseif cases that do not apply on the first iteration of the while-loop...]
                } else {
                    zendi_convert_scalar_to_number(op1, op1_copy, result);
                    zendi_convert_scalar_to_number(op2, op2_copy, result);
                    converted = 1;
                }
[...]

首次执行此代码时op1 ~ 'test'op2~0。 (〜意思是“大致是”,因为内部代表有点不同,但这里并不重要。)
但是没有TYPE_PAIR(IS_STRING,IS_LONG)的情况,所以它命中默认值:branch。有一些if条件用于处理对象,但操作数都不是一个对象,所以它转到操作数被转换的部分(一次)。
同样没有if-conditon适用,所以它命中最后一个else-branch,将两个操作数转换为数字。
'test'转换为00保留0 然后再次执行while循环,现在使用TYPE_PAIR(IS_LONG,IS_LONG) - 第一种情况。并且现在两个操作数相等 - &gt; in_array()返回true。

......是的,我发现这也令人困惑; - )