How to Use PHP's in_array() Function for Array Searches
This article explains PHP's in_array() function, detailing its syntax, parameters, return values, and demonstrates basic usage, strict mode comparison, and searching within multidimensional arrays through clear code examples and explanations for developers.
PHP provides many built‑in functions for handling arrays, and in_array() is one of the most useful. It checks whether a specific value exists in a given array, returning TRUE if found and FALSE otherwise.
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): when set to TRUE , in_array() also compares data types.
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 "Banana not found!";
}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 "3 not found!";
}Output:
3 not found!Explanation: Although the string "3" exists in the array, strict mode requires both value and type to match. Since the array element is a string and the comparison is strict, in_array() does not find a match.
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 "Mary not found!";
}Output:
Found Mary!Explanation: The function can also search for an entire sub‑array. Since the exact associative array for Mary exists in $people , the function returns TRUE and prints the success message.
Summary
The in_array() function is a practical tool in PHP for quickly checking whether a specific element exists in an array. Developers can enable strict mode to compare both value and type, and the function also works with multidimensional arrays.
In everyday PHP development, determining the presence of an element in an array is a common task, and in_array() provides a concise solution.
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.