Reputation: 161
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?
Upvotes: 5
Views: 14713
Reputation: 10793
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.
Upvotes: 3
Reputation: 26385
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.
$a=array("a"=>"1","b"=>"2","c"=>"2");
print_r(array_keys($a, "2"));
Array
(
[0] => b
[1] => c
)
Upvotes: 9
Reputation: 21759
use array_keys instead:
<?php
$a=array("a"=>"1","b"=>"2","c"=>"2");
echo array_keys(array($a, "2");
?>
Upvotes: 1