Understanding PHP in_array() Pitfalls and Proper Usage
This article explains how the PHP in_array() function can return misleading results when the strict comparison flag is omitted, demonstrates the issue with a simple code example, and shows the correct usage as well as a comparable JavaScript approach using indexOf().
The in_array() function in PHP checks whether a value exists in an array, but if the third parameter (strict comparison) is omitted the function may produce unintuitive results because it performs loose comparison.
Consider the following PHP code:
<code><?php
$arr = [true, false];
$f = in_array('Hello', $arr);
if ($f) {
echo 'in array';
} else {
echo 'not found';
}
// Output: in array</code>Even though the string 'Hello' is not present in $arr , the function returns true because the string is loosely compared to true . Adding the strict flag resolves the problem:
<code>in_array('Hello', $arr, true)</code>In JavaScript the same issue does not occur; developers typically use indexOf() for array searches, which performs a strict comparison by default.
For a visual illustration of the JavaScript approach, see the accompanying image in the original article.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.