Home > Backend Development > PHP Tutorial > Why Does `in_array()` Return True for a Non-Existent Value in PHP?

Why Does `in_array()` Return True for a Non-Existent Value in PHP?

Barbara Streisand
Release: 2024-12-22 11:45:09
Original
164 people have browsed it

Why Does `in_array()` Return True for a Non-Existent Value in PHP?

In-array's Peculiar Behavior with TRUTH

PHP's in_array() function exhibits an unexpected behavior when working with an array containing the boolean TRUE.

Let's consider the following array:

$arr = [TRUE, "some string", "something else"];
Copy after login

Surprisingly, in_array("test", $arr) returns true, even though "test" is not in the array. The same unusual result arises with array_search("test", $arr), which returns 0.

This behavior is not a bug, but a well-documented feature.

Strictly Speaking: Understanding the Third Parameter

Both in_array() and array_search() possess an optional third parameter, $strict, which defaults to FALSE.

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ])
Copy after login

This means that, by default, both functions employ loose comparison (==). They evaluate values solely on equality, disregarding their types. Consequently, in the given example, TRUE == "any non-empty string" returns true because of type juggling.

Enforcing Rigor: Setting $strict to TRUE

To ensure accurate comparisons, you can set $strict to TRUE. Doing so forces PHP to use strict comparison (===), checking both the value and type of the values it compares.

$result = in_array("test", $arr, TRUE);
var_dump($result); // Output: bool(false)
Copy after login

In this case, in_array() correctly returns false, as expected.

Remember that understanding the nuances of type juggling and the role of $strict is crucial when using in_array() and array_search(). These functions offer powerful search capabilities, but their behavior can be unpredictable if these subtleties are overlooked.

The above is the detailed content of Why Does `in_array()` Return True for a Non-Existent Value in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template