Why does php's in_array return true if passed a 0?

The reason behind in_array returning True could be the string-to-number conversion. When a string is passed to the function, it returns 0, which is the value that needs to be searched for.

PHP uses loose juggling, i.e. using == instead of === when elements are compared. Hence, their values are compared and not the types.

Another reason is type juggling, which means a variable type is dealt with in the context of the code.

For example- when a float value is assigned to a variable, it becomes a floating-point value. It behaves in a way when a string is casted to an integer

To avoid this kind of behaviour, a third parameter can be passed, which compares the data in a strict mode, wherein the values as well as types are compared.

Below is how the function behave when a string is passed −


 Live Demo

echo intval("Hello");


This will produce the following output −