Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search array and return multiple matches [duplicate]

Tags:

php

For example if I am searching for a key with a value 5 in my array $cake, I could use the following code:

$cake = array("a"=>6,"b"=>5,"c"=>6);
echo array_search(5, $cake, true); // returns "b";

But if my $cake array contains multiple matches, only the first match is returned:

$cake = array("a"=>6,"b"=>5,"c"=>5,"d"=>5,"e"=>5);
echo array_search(5, $cake, true); // returns "b";

How can I return multiple matches as an array? Like this:

$cake = array("a"=>6,"b"=>5,"c"=>5,"d"=>5,"e"=>5);
// return array("b","c","d","e");
like image 237
user2217162 Avatar asked Jul 29 '13 15:07

user2217162


People also ask

How do I find and return multiple matches in Excel?

VLOOKUP with Multiple Results To lookup multiple matches with the VLOOKUP Function you need to create a helper column within the table of data. The helper column uses the COUNTIF Function to create a unique ID for each instance. The helper column must be the leftmost column within the data set.

Does VLOOKUP work with multiple matches?

An immediate solution that comes to mind is using the Excel VLOOKUP function, but the problem is that it can only return a single match. Vlookup for multiple values can be done via a combined use of several functions.


1 Answers

As noted in the docs:

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.

print_r(array_keys($cake, 5, true));
like image 115
Jason McCreary Avatar answered Nov 03 '22 20:11

Jason McCreary