Skip to content
Advertisement

Php, in_array, 0 value

I was trying to understand the in_array behavior at the next scenario:

JavaScript

The returned value of the in_array() is boolean true. As you can see there is no value equal to 0, so if can some one please help me understand why does the function return true?

Advertisement

Answer

This is a known issue, per the comments in the documentation. Consider the following examples:

JavaScript

To avoid this, provide the third paramter, true, placing the comparison in strict mode which will not only compare values, but types as well:

JavaScript

Other work-arounds exist that don’t necessitate every check being placed in strict-mode:

JavaScript

But Why?

The reason behind all of this is likely string-to-number conversions. If we attempt to get a number from “Bye”, we are given 0, which is the value we’re asking to look-up.

JavaScript

To confirm this, we can use array_search to find the key that is associated with the matching value:

JavaScript

In this, the returned key is 2, meaning 0 is being found in the conversion of Bye to an integer.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement