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

The in_array() in PHP can return unexpected results when searching for the value 0 due to PHP's type juggling behavior. By default, in_array() uses loose comparison (==) instead of strict comparison (===).

The Problem

When PHP performs loose comparison, it converts string values to integers for comparison. Non-numeric strings convert to 0, causing false matches ?

<?php
$array = ["apple", "banana", "cherry"];
$result = in_array(0, $array);
var_dump($result);
?>
bool(true)

Why This Happens

PHP converts strings to integers when comparing with numbers. Non-numeric strings become 0 ?

<?php
echo intval("apple") . "<br>";
echo intval("hello") . "<br>";
echo intval("123abc") . "<br>";
?>
0
0
123

The Solution − Strict Comparison

Use the third parameter $strict set to true to enable strict comparison ?

<?php
$array = ["apple", "banana", "cherry"];

// Loose comparison (default)
$loose = in_array(0, $array);

// Strict comparison
$strict = in_array(0, $array, true);

echo "Loose: " . ($loose ? 'true' : 'false') . "<br>";
echo "Strict: " . ($strict ? 'true' : 'false') . "<br>";
?>
Loose: true
Strict: false

Comparison Table

Comparison Type Function Call Result for 0 vs "apple"
Loose (==) in_array(0, $array) true
Strict (===) in_array(0, $array, true) false

Conclusion

Always use the third parameter true in in_array() when searching for exact matches to avoid unexpected type conversion behavior. This ensures both value and type are compared.

Updated on: 2026-03-15T08:33:13+05:30

381 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements