in_array()无法按预期工作

Seb*_*ian 12 php arrays

对于这个数组($options):

Array (
    [0] => 0
    [1] => 1
    [2] => 2
)
Run Code Online (Sandbox Code Playgroud)

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  
Run Code Online (Sandbox Code Playgroud)

为什么?

Tim*_*per 25

这是因为0 == "string"是真的,并且0是数组的一个元素.

将该参数设置$strictin_array设置为true:

$this->assertTrue( in_array('Bug', $options, true) );
Run Code Online (Sandbox Code Playgroud)


lyn*_*nks 6

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

$this->assertTrue( in_array('Bug', $options, true) ); 
Run Code Online (Sandbox Code Playgroud)

这将确保比较类型严格,并应解决您的问题.