Using PHP in_array() Function to Check for Values in Arrays
This article explains PHP's in_array() function, its syntax, parameters, return values, and demonstrates basic usage, strict mode, and multidimensional array searches with clear code examples, including how to handle type comparison and practical output handling in typical PHP development.
In PHP, the built‑in in_array() function 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 ] )Parameters:
$needle : the value to search for (any type).
$haystack : the array to search.
$strict (optional): when TRUE , also compare types.
Return value:
Returns TRUE if the value is found, otherwise FALSE .
Example 1: Basic usage
$fruits = array("apple", "banana", "orange", "grape");
if (in_array("banana", $fruits)) {
echo "找到了 banana!";
} else {
echo "没有找到 banana!";
}Output: 找到了 banana!
Example 2: Strict mode
$numbers = array(1, 2, "3", 4, 5);
if (in_array("3", $numbers, true)) {
echo "找到了 3!";
} else {
echo "没有找到 3!";
}Output: 没有找到 3!
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 "找到了 Mary!";
} else {
echo "没有找到 Mary!";
}Output: 找到了 Mary!
Summary
The in_array() function is a practical tool for quickly checking the presence of an element in an array, with optional strict type comparison and the ability to search multidimensional arrays, making it valuable in everyday PHP development.
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.