5

I'm trying to search an array and return multiple keys

<?php
$a=array("a"=>"1","b"=>"2","c"=>"2");
echo array_search("2",$a);
?>

With the code above it only returns b, how can I get I to return b and c?

Mike Johnston
  • 161
  • 1
  • 1
  • 4

3 Answers3

9

As it says in the manual for array_search:

To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.


Example:

$a=array("a"=>"1","b"=>"2","c"=>"2");
print_r(array_keys($a, "2"));

Result:

Array
(
    [0] => b
    [1] => c
)
user3942918
  • 25,539
  • 11
  • 55
  • 67
3

I am adding this in case someone finds it helpful. If you're doing with multi-dimensional arrays. Suppose you have this

        $a = array(['user_id' => 2, 'email_id' => 1], ['user_id' => 2, 'email_id' => 2, ['user_id' => 3, 'email_id' => 1]]);

You want to find email_id of user_id 2. You can do this

        print_r(array_keys(array_column($a, 'user_id'), 2));

This will return [0,1]

Hope this helps.

Koushik Das
  • 9,678
  • 3
  • 51
  • 50
1

use array_keys instead:

<?php
$a=array("a"=>"1","b"=>"2","c"=>"2");
echo array_keys(array($a, "2");
?>
taxicala
  • 21,408
  • 7
  • 37
  • 66