Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in_array() does not work as expected [duplicate]

Tags:

arrays

php

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_array('RockAndRoll', $options ) ); // TRUE  

Why?

like image 798
Sebastian Avatar asked Oct 06 '11 01:10

Sebastian


2 Answers

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) );
like image 104
Tim Cooper Avatar answered Oct 17 '22 02:10

Tim Cooper


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.

like image 33
lynks Avatar answered Oct 17 '22 02:10

lynks