[PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8]
array_search — Searches the array for a given value and returns the first corresponding key if successful
Description
array_search[mixed $needle
, array $haystack
, bool $strict
= false
]: int|string|false
Parameters
needle
The searched value.
Note:
If
needle
is a string, the comparison is done in a case-sensitive manner.
haystack
The array.
strict
If the third parameter strict
is set to true
then the array_search[] function will search for identical elements in the haystack
. This means it will also perform a
strict type comparison of the needle
in the haystack
, and objects must be the same instance.
Return Values
Returns the key for needle
if it is found in the array, false
otherwise.
If needle
is found in haystack
more than once, the first matching key is returned. To return the keys for all matching
values, use array_keys[] with the optional search_value
parameter instead.
Warning
This function may return Boolean false
, but may also return a non-Boolean value which evaluates to false
. Please read the section on Booleans for more
information. Use the === operator for testing the return value of this function.
Examples
Example #1 array_search[] example
See Also
- array_keys[] - Return all the keys or a subset of the keys of an array
- array_values[] - Return all the values of an array
- array_key_exists[] - Checks if the given key or index exists in the array
- in_array[] - Checks if a value exists in an array
turabgarip at gmail dot com ¶
5 years ago
About searcing in multi-dimentional arrays; two notes on "xfoxawy at gmail dot com";
It perfectly searches through multi-dimentional arrays combined with array_column[] [min php 5.5.0] but it may not return the values you'd expect.
Since array_column[] will produce a resulting array; it won't preserve your multi-dimentional array's keys. So if you check against your keys, it will fail.
For example;
Here, you could expect that the $found_key would be "5" but it's NOT. It will be 1. Since it's the second element of the produced array by the array_column[] function.
Secondly, if your array is big, I would recommend you to first assign a new variable so that it wouldn't call array_column[] for each element it searches. For a better performance, you could do;
opencart dot ocfilter at gmail dot com ¶
11 months ago
Be careful!
But, in php 8
thinbegin at gmail dot com ¶
4 years ago
Despite PHP's amazing assortment of array functions and juggling maneuvers, I found myself needing a way to get the FULL array key mapping to a specific value. This function does that, and returns an array of the appropriate keys to get to said [first] value occurrence.
function array_recursive_search_key_map[$needle, $haystack] {
foreach[$haystack as $first_level_key=>$value] {
if [$needle === $value] {
return array[$first_level_key];
} elseif [is_array[$value]] {
$callback = array_recursive_search_key_map[$needle, $value];
if [$callback] {
return array_merge[array[$first_level_key], $callback];
}
}
}
return false;
}
usage example:
-------------------
$nested_array = $sample_array = array[
'a' => array[
'one' => array ['aaa' => 'apple', 'bbb' => 'berry', 'ccc' => 'cantalope'],
'two' => array ['ddd' => 'dog', 'eee' => 'elephant', 'fff' => 'fox']
],
'b' => array[
'three' => array ['ggg' => 'glad', 'hhh' => 'happy', 'iii' => 'insane'],
'four' => array ['jjj' => 'jim', 'kkk' => 'kim', 'lll' => 'liam']
],
'c' => array[
'five' => array ['mmm' => 'mow', 'nnn' => 'no', 'ooo' => 'ohh'],
'six' => array ['ppp' => 'pidgeon', 'qqq' => 'quail', 'rrr' => 'rooster']
]
];
$search_value = 'insane';
$array_keymap = array_recursive_search_key_map[$search_value, $nested_array];
var_dump[$array_keymap];
// Outputs:
// array[3] {
// [0]=>
// string[1] "b"
// [1]=>
// string[5] "three"
// [2]=>
// string[3] "iii"
//}
----------------------------------------------
But again, with the above solution, PHP again falls short on how to dynamically access a specific element's value within the nested array. For that, I wrote a 2nd function to pull the value that was mapped above.
function array_get_nested_value[$keymap, $array]
{
$nest_depth = sizeof[$keymap];
$value = $array;
for [$i = 0; $i < $nest_depth; $i++] {
$value = $value[$keymap[$i]];
}
return $value;
}
usage example:
-------------------
echo array_get_nested_value[$array_keymap, $nested_array]; // insane
cue at openxbox dot com ¶
19 years ago
If you are using the result of array_search in a condition statement, make sure you use the === operator instead of == to test whether or not it found a match. Otherwise, searching through an array with numeric indicies will result in index 0 always getting evaluated as false/null. This nuance cost me a lot of time and sanity, so I hope this helps someone. In case you don't know what I'm talking about, here's an example:
stefano@takys dot it ¶
11 years ago
for searching case insensitive better this:
nordseebaer at gmx dot de ¶
2 years ago
It's really important to check the return value is not false! I used array_search[] to determine the index of an value to unset this value and then realized that $arr[false] === $arr[0] !
So always check the return of array_search!
yasien dot dwieb at gmail dot com ¶
2 years ago
Beware when using array_search to a mix of string and integer where prefixes of keys may collide, as in my case I have encountered the following situation:
Assume you have the following array:
$index1 and $index2 will be the same
after using strict type search:
it will not find $index1 at all while returning a correct value for $index2;
maciej at speccode dot com ¶
7 years ago
FYI, remember that strict mode is something that might save you hours.
If you're searching for a string and you have a "true" boolean on the way - you will get it as result [first occurrence]. Example below:
RichGC ¶
16 years ago
To expand on previous comments, here are some examples of
where using array_search within an IF statement can go
wrong when you want to use the array key thats returned.
Take the following two arrays you wish to search:
n-regen ¶
13 years ago
If you only know a part of a value in an array and want to know the complete value, you can use the following function:
The function returns the complete first value of $haystack that contains $needle.
codeslinger at compsalot dot com ¶
12 years ago
one thing to be very aware of is that array_search[] will fail if the needle is a string and the array itself contains values that are mixture of numbers and strings. [or even a string that looks like a number]
The problem is that unless you specify "strict" the match is done using == and in that case any string will match a numeric value of zero which is not what you want.
-----
also, php can lookup an index pretty darn fast. for many scenarios, it is practical to maintain multiple arrays, one in which the index of the array is the search key and the normal array that contains the data.
stooshie at gmail dot com ¶
10 years ago
Example of a recursive binary search that returns the index rather than boolean.
helenadeus at gmail dot com ¶
13 years ago
I was trying to use array_search to retrieve all the values that match a given needle, but it turns out only the first match key is returned. I built this little function, which works just like array_search, but returns all the keys that match a given needle instead. The output is an array.
azaozz, gmail ¶
13 years ago
Expanding on the comment by hansen{}cointel.de:
When searching for a string and the array contains 0 [zero], the string is casted to [int] by the type-casting which is always 0 [perhaps the opposite is the proper behaviour, the array value 0 should have been casted to string]. That produces unexpected results if strict comparison is not used:
This will return:
str1 = 0, str2 = 0, str3 = 0, str1 strict = 1, str2 strict = 2, str3 strict = 3
andreas dot damm at maxmachine dot de ¶
14 years ago
Combining syntax of array_search[] and functionality of array_keys[] to get all key=>value associations of an array with the given search-value:
Usage:
Will return:
array[4] {
["pre"] =>
string[1] "2"
[1] =>
int[2]
[4] =>
string[1] "2"
["post"] =>
int[2]
}
array[2] {
["pre"] =>
string[1] "2"
[4] =>
string[1] "2"
}
array[2] {
[1] =>
int[2]
["post"] =>
int[2]
}
kermes [at] thesevens [dot] net ¶
15 years ago
A variation of previous searches that returns an array of keys that match the given value: