Definition and Usage
- PHP Version
- 4.0.5+
The array_search()
function searches an array for a value.
It returns the key (or index) of the first matching element if found, or false if the value is not present.
Features
- If the searched value is a string, the search is case-sensitive.
- If multiple matches are found, only the key (or index) of the first matching value is returned.
- If the third parameter is set to
true
, the search uses strict mode, which requires the data type to match exactly.
By default, the number2
and the string'2'
are considered equal, but in strict mode,2
and'2'
are not equal.
Basic Example
PHP
// Example 1: Using array_search() with a simple array
$arr = ['a', 'b', 'c'];
$key = array_search('c', $arr);
var_dump($key); // Output: int(2)
$notFound = array_search('d', $arr);
var_dump($notFound); // Output: bool(false)
// Example 2: Using array_search() with an associative array
$fruits = [
'apple' => 'red',
'banana' => 'yellow',
'cherry' => 'red'
];
$colorToFind = array_search('red', $fruits);
var_dump($colorToFind); // Output: string(5) "apple"
Syntax
array_search(mixed $needle, array $haystack, bool $strict = false): int|string|false
Parameters
$needle |
The value to search for.
If it is a string, the comparison is case-sensitive. |
---|---|
$haystack |
The array in which to search. |
$strict |
Optional. Determines whether the comparison should check for exact data type match (true or false ).
|
Return Values
If a match is found, array_search()
returns the key (or index) of the first matching value. If no match is found, it returns false
.
$fruits = [
'apple' => 'red',
'banana' => 'yellow',
'cherry' => 'red'
];
// Searches for the value 'red' in the $fruits array and returns the key (or index) of the first match
$colorToFind = array_search('red', $fruits);
// There are two keys with the value 'red' in the $fruits array: 'apple' and 'cherry'.
// $colorToFind is assigned the key of the first matching value ('red').
// Therefore, $colorToFind will be 'apple'.
var_dump($colorToFind); // Output: string(5) 'apple'
Important Note on Comparing Return Values
When using array_search()
, always use the strict equality operator (===
) to check the return value.
The following example shows the difference between using non-strict equality (==
) and strict equality (===
) to evaluate the search result.
$numbers = [0, "0", false, null];
$searchValue = 0;
$result = array_search($searchValue, $numbers, true);
if ($result == false) {
echo "The value $searchValue was not found in the array.";
} else {
echo "The value $searchValue is located at index $result.";
}
// Incorrect result!!!
// Output: 'The value 0 was not found in the array.'
if ($result === false) {
echo "The value $searchValue was not found in the array.";
} else {
echo "The value $searchValue is located at index $result.";
}
// Output: 'The value 0 is located at index 0.'
This example demonstrates how to search an array using array_search()
and how to verify the result. The key point is understanding the difference between the two comparison methods:
- In the first
if
statement, the non-strict equality operator (==
) is used, which treatsfalse
and0
as equal. This results in the incorrect message: "The value 0 was not found in the array." - In the second
if
statement, the strict equality operator (===
) is used, which requires both the value and the data type to match. This avoids the incorrect message.
In conclusion, using the strict equality operator (===
) ensures accurate evaluation of the return value and improves code reliability.
Practical Examples
The array_search()
function is commonly used for the following purposes.
Searching for an Existing Value
$numbers = [1, 2, 3, 4, 2, 5, 6];
$searchValue = 2;
if (array_search($searchValue, $numbers) !== false) {
echo 'The value exists in the array.';
} else {
echo 'The value does not exist in the array.';
}
// Output: 'The value exists in the array.'
This example demonstrates how to search for a value ($searchValue, here 2) in the $numbers array to check if it exists. The array_search()
function returns the key (or index) of the first matching value if found, or false
if not found. This code outputs: 'The value exists in the array.'
Deleting or Modifying a Found Value
$products = [
'apple' => 1.99,
'banana' => 0.99,
'cherry' => 2.49
];
$targetPrice = 1.00; // Price to search for
$key = array_search($targetPrice, $products);
if ($key !== false) {
unset($products[$key]); // Remove the found value
// Or modify the value: $products[$key] = new price;
} else {
echo 'Product or price not found.';
}
In this example, the code searches for $targetPrice
(1.00) and either removes or modifies the value in the array. array_search()
checks if the product exists, and if found, deletion or modification is performed.
Searching in a Two-Dimensional Array
$students = [
['name' => 'Alice', 'age' => 20],
['name' => 'Bob', 'age' => 22],
['name' => 'Charlie', 'age' => 21]
];
$searchName = 'Bob';
foreach ($students as $key => $student) {
if (array_search($searchName, $student) !== false) {
echo "Found student named $searchName. Student index: $key";
break;
}
}
// Output: 'Found student named Bob. Student index: 1'
Code Explanation
The foreach()
loop is commonly used to iterate over arrays or objects.
In this example, we search for a student's name in the two-dimensional $students array and output the corresponding information. array_search()
searches within each student array for the name, returning the student's index. Once found, the loop breaks and the student's information is displayed. This pattern is useful for student management or data lookup scenarios.
Finding the Position of a Specific Value in an Array
$numbers = [3, 5, 2, 8, 10, 6];
$searchValue = 8;
$key = array_search($searchValue, $numbers);
if ($key !== false) {
echo "The value $searchValue is located at index $key.";
} else {
echo "The value $searchValue does not exist in the array.";
}
// Output: 'The value 8 is located at index 3.'
References
See also
- PHP in_array() Function – Check if a Value Exists in an Array
- PHP array_key_exists() Function – Check if a Key Exists in an Array
- PHP array_filter() Function – Filter Array Elements with a Callback
- PHP array_reduce() Function – Reducing an Array to a Single Value
- PHP array_keys() Function – Get a List of Array Keys
- JavaScript Array find() Function – Finding Elements with a Callback Function