Using PHP in_array() Function: Syntax, Parameters, Return Values, and Practical Examples
This article explains PHP's in_array() function, covering its syntax, parameters, return values, and demonstrating its usage with basic, strict mode, and multidimensional array examples to help developers quickly determine element presence in arrays.
PHP provides many built‑in functions for handling arrays, 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 ] )Parameters:
$needle : the value to search for; it can be of any type.
$haystack : the array in which to search.
$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 "Did not find banana!";
}Output:
Found banana!Explanation: The array $fruits contains four fruit strings. in_array() finds "banana" and the script prints the success message.
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 mixes integers and a string "3". With strict mode enabled, the string "3" does not match the integer 3, so the function returns 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 multidimensional array $people holds several associative arrays. in_array() can check for an exact match of an associative array, and it successfully finds the entry for Mary.
Summary
The in_array() function is a very practical PHP utility for quickly checking whether a specific element exists in an array, with optional strict type comparison and support for multidimensional arrays.
In everyday PHP development, determining element presence is a common task, and in_array() provides a concise and efficient 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.