PHP in_array () / array_search () odd behavior

I found some odd behavior when I used the in_array() PHP function. I have an array like this:

 $arr = [TRUE, "some string", "something else"]; 

Now, if I want to check if there is a "test" in the array, obviously not, but in_array() still returns TRUE, why?

 $result = in_array("test", $arr); var_dump($result); // Output: bool(true) 

The same thing happens when using array_search() :

 $result = array_search("test", $arr); var_dump($result); // Output: int(0) 

I thought it was possible that the TRUE value in the array automatically caused the function to return TRUE for each result without checking the rest of the array, but I could not find any documentation that could offer this very unusual functionality.

+5
source share
2 answers

This behavior of the in_array() and array_search() functions is not an error, but rather a well-documented behavior.

Both functions have a third optional parameter named $strict , which is FALSE by default:

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

mixed array_search (mixed $ needle, $ haystack [, bool $ strict = false] array)

Now this means that, by default, both functions use weak ( == ) comparisons to compare values. Therefore, they check to see if the values ​​match after manipulating with PHP types and without type checking. Because of this, in your example TRUE == "any none emtpy string" has the value TRUE.

So, setting the third parameter to TRUE when calling the function, you say that PHP should use strict ( === ) comparison, and it should check the value AND type of values ​​when comparing.

See this as a link: How are the equality comparison operators between equal (== double equals) and identical (=== triple equals) different?

+8
source

You are right, a logical one can really cause this. Set the strict flag to in_array , this way the element type is also checked (basically this is the same as using === ):

 if (in_array("username", $results, true)) // do something if (in_array("password", $results, true)) // do something if (in_array("birthday", $results, true)) // do something 
+2
source

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


All Articles