What is the reason for this strange PHP behavior?

I have the following code:

$data = array(); // prep array $data['aardvark'] = true; print_r($data); // output array echo "\n"; var_dump(in_array('zebra', $data)); 

The output is as follows:

 Array ( [aardvark] => 1 ) bool(true) 

Despite the fact that zebra clearly not in the array. This seems to be related to the PHP free type system. (bool) 'zebra' is true , and there is true in the array, so in_array returns true?

I think I can see the logic, but it is corrupted. Is this a PHP bug?

Greetings.

+6
source share
4 answers

Not a mistake. You have it for sure. In order to correctly find what you are looking for, you will need to do this:

 if (in_array('zebra', $data, true)) { 

Although this is likely to be rare if you store different types of data in the same array (strings and booleans). If you store data that is not a list, most likely you should use an object.

+4
source

You're right. in_array()

bool in_array (mixed $ needle, array $ haystack [, bool $ strict = FALSE])

You must set the third parameter to true if you want in_array() also test the type. Otherwise it will make a free comparison

 var_dump(in_array('zebra', $data, true)); 

This is usually not a problem, because (in a clean design) usually all values ​​are of the same type that you know before you call in_array() , and therefore you can avoid calling it with inappropriate types.

+3
source

This is because the string 'zebra' not empty, and a non-empty string other than '0' is interpreted by PHP as true , and since there is a corresponding value in your array, you get true as the result.

PHP did the conversion from string to boolean. To avoid this conversion, you need to pass the third argument as true to in_array :

 var_dump(in_array('zebra', $data, true)); 
+2
source

"This is not a mistake, this is a feature!" =)

Try executing in_array("zebra", $data, true); , which will force a "strict" check (that is, it will check the type of your variables).

+1
source

Source: https://habr.com/ru/post/902235/


All Articles