开发者

in_array() does not work as expected [duplicate]

This question already has answers here: PHP in_array() / array_search() odd behaviour (2 answers) Closed 6 years ago.

For this array ($options):

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

PHP returns 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_开发者_如何学Carray('RockAndRoll', $options ) ); // TRUE  

Why?


This is because 0 == "string" is true, and 0 is an element of the array.

Set the parameter $strict in in_array to true:

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


Try adding a third parameter to your function calls;

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

This will ensure the comparisons are type-strict, and should solve your problem.


Add a third argument to in_array() and set it to TRUE.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜