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?

1
  • use array_keys function Commented Oct 11, 2015 at 3:45

3 Answers 3

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
)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, is there a way to display the output as just b,c or b c?
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.

Comments

1

use array_keys instead:

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

2 Comments

Thanks for the answers taxicala but what I was looking for is something that allows me to find all instances of the word im searching for not just the first instance.
it's what array_keys does

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.