Felipe Weckx

PHP: in_array and arrays with a true item

A very important parameter of the in_array PHP function is the $strict parameter. It has the default value of FALSE. But what exactly does it do? Let’s look at the following code:

The output will be as expected:

However, if we add to the array $array a new item with the value true:

Then the output will be:

Which means that the in_array returned true even though there’s no salmon item in $array! That is because by default the in_array functio uses PHP’s “loose comparison”, that is, it uses the  “==” operator to check if the value is in the array (more information on http://php.net/manual/en/types.comparisons.php) so any non-empty value that is compared to true returns true. That can cause a nasty bug that is very hard to find and understand. To solve it we can pass the $strict parameter as true:

Now the comparison will behave as expected. That kind of mistake can be easily prevented if the software is developed using TDD with a good test coverage and test cases, but otherwise it can be very tricky to be found.

Deixe um comentário

Leave a Reply

Your email address will not be published.