【问题标题】:in_array() does not work as expected [duplicate]in_array() 没有按预期工作[重复]
【发布时间】:2011-12-01 22:41:52
【问题描述】:

对于这个数组($options)

Array (
    [0] => 0
    [1] => 1
    [2] => 2
)

PHP 返回 TRUE:

$this->assertTrue( in_array('Bug', $options ) );         // TRUE
$this->assertTrue( in_array('Feature', $options ) );     // TRUE
$this->assertTrue( in_array('Task', $options ) );        // TRUE
$this->assertTrue( in_array('RockAndRoll', $options ) ); // TRUE  

为什么?

【问题讨论】:

  • @Phil:哦,是的,我是这么想的,在我看到你的回复之前就把它删除了。

标签: php arrays


【解决方案1】:

in_array() 添加第三个参数并将其设置为TRUE

【讨论】:

    【解决方案2】:

    这是因为0 == "string" is true,而0是数组的一个元素。

    in_array中的参数$strict设置为true:

    $this->assertTrue( in_array('Bug', $options, true) );
    

    【讨论】:

      【解决方案3】:

      尝试在函数调用中添加第三个参数;

      $this->assertTrue( in_array('Bug', $options, true) ); 
      

      这将确保比较是类型严格的,并且应该可以解决您的问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-17
        • 2012-11-01
        • 1970-01-01
        • 2021-08-14
        • 2013-03-25
        • 2021-01-16
        • 2015-10-16
        • 2017-12-22
        相关资源
        最近更新 更多