array_search() is a built in PHP function that searches the array for a given value and returns the first corresponding key if successful.
Syntax
array_search ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) : mixed
Support: (PHP 4 >= 4.0.5, PHP 5, PHP 7)
Parameters of array_search()
$needle
- The
$needleparameter is required. - It refers to the value that needs to be searched in the array.
$haystack
- The
$haystackparameter is required. - It refers to the original array, on which search operation is performed.
$strict
- The
$haystackparameter is an optional one. - It can be set to
trueorfalse, and refers to the strictness of search. - The default value of this parameter is false.
- Example: when it is set to true, the string 45 is not same as number 45.
Return Values
- The key of a value is returned if it is found in an array, otherwise false.
- If the value is found in the array more than once, the first matching key is returned.
Example #1 – Search an array for the value “Jerusalem” and return its key
$records = [
'New Delhi' => 'India',
'Madrid' => 'Spain',
'Israel' => 'Jerusalem',
'Amsterdam' => 'Netherlands'
];
$countries = array_search("Jerusalem", $records);
print_r($countries);
The above example will output:
Israel
Example #2 – With third parameter “strict” mode
$records = [
'x' => '10',
'y' => 10,
'z' => '10'
];
echo 'Without strict parameter: ';
echo array_search(10, $records);
echo 'With strict parameter: ';
echo array_search(10, $records, true);
The above example will output
Israel
Example #3 – You don’t have to write your own function to search through a multidimensional array, (example with array_column())
$records = [
[
'id' => 12,
'country' => 'India',
'capital' => 'New Delhi',
],
'Spain' => [
'id' => 24,
'country' => 'Spain',
'capital' => 'Madrid',
],
[
'id' => 91,
'country' => 'Israel',
'capital' => 'Jerusalem',
],
'Netherlands' => [
'id' => 121,
'country' => 'Netherlands',
'capital' => 'Amsterdam',
]
];
$countries = array_column($records, 'country');
print_r($countries);
$key = array_search('Israel', array_column($records, 'country'));
echo 'Key: ' . $key;
The above example will output
Array
(
[0] => India
[1] => Spain
[2] => Israel
[3] => Netherlands
)
Key: 2
Hope you find this helpful
Related Articles
Deepen your understanding with these curated continuations.
PHP 5 min read
PHP Interview Questions
This tutorial explains with syntax and an example of how to flatten a multi-dimensional array based on the value of depth specified in the Laravel framework.
Vishnu
PHP 5 min read
How to build query string from an array with http_build_query in PHP
How to build query string from an array with http_build_query in PHP
Vishnu
PHP 5 min read
Convert Hex Color to RGB or RGBA in PHP
A PHP helper function that converts any hex color code to rgb() or rgba() — handles 3-char shorthand, optional opacity, and the # prefix. With usage examples.
Vishnu