How to Use PHP's in_array() Function to Check for Values in an Array
This article explains the PHP in_array() function, its syntax, parameters, return values, and demonstrates basic usage, strict mode, and multidimensional array searches with clear code examples and explanations.
PHP provides many built‑in functions for array handling, and in_array() is a particularly useful one that checks whether a specific value exists in a given array.
Syntax:
bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )Parameter Description:
$needle : the value to search for, can be of any type.
$haystack : the array to search in.
$strict (optional): if set to TRUE , in_array() also checks the data type.
Return Value:
If the value is found, the function returns TRUE ; otherwise it returns FALSE .
Example 1: Basic Usage
$fruits = array("apple", "banana", "orange", "grape");
if (in_array("banana", $fruits)) {
echo "Found banana!";
} else {
echo "Did not find banana!";
}Output:
Found banana!Explanation: The array $fruits contains "banana", so in_array() returns TRUE and the message "Found banana!" is printed.
Example 2: Using Strict Mode
$numbers = array(1, 2, "3", 4, 5);
if (in_array("3", $numbers, true)) {
echo "Found 3!";
} else {
echo "Did not find 3!";
}Output:
Did not find 3!Explanation: The array $numbers contains the string "3" but also numeric values. With strict mode enabled, in_array() requires both value and type to match, so it does not consider the string "3" equal to the integer 3, resulting in FALSE .
Example 3: Searching in a Multidimensional Array
$people = array(
array("name" => "John", "age" => 20),
array("name" => "Mary", "age" => 30),
array("name" => "David", "age" => 25)
);
if (in_array(array("name" => "Mary", "age" => 30), $people)) {
echo "Found Mary!";
} else {
echo "Did not find Mary!";
}Output:
Found Mary!Explanation: The two‑dimensional array $people contains an associative array that exactly matches the searched sub‑array, so in_array() returns TRUE and prints "Found Mary!".
Summary
The in_array() function is a very practical PHP tool for quickly checking whether a specific element exists in an array, with optional strict mode for type‑sensitive comparisons, and it also works with multidimensional arrays.
In everyday PHP development, checking array membership is common, and in_array() provides a concise solution; the examples above illustrate its basic usage, strict mode behavior, and how to apply it to nested arrays.
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.