5

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");
Cœur
  • 37,241
  • 25
  • 195
  • 267
user2217162
  • 897
  • 1
  • 9
  • 20

3 Answers3

12

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));
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
0

you can do this:

for($index = 0; $index <= count($cake); $index++){
    if(!array_search(5, $cake[$index], true) == false){
        echo array_search(5, $cake[$index], true);
    }
}
HamZa
  • 14,671
  • 11
  • 54
  • 75
guy
  • 40
  • 7
0

You can use array_intersect.

array_intersect — Computes the intersection of arrays

 $matches = array_keys(array_intersect($cake, array(5)));
 print_r($matches);

Outputs

Array
(
    [0] => b
    [1] => c
    [2] => d
    [3] => e
)
Orangepill
  • 24,500
  • 3
  • 42
  • 63