Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Array Search Return Multiple Keys

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?

like image 760
Mike Johnston Avatar asked Oct 11 '15 03:10

Mike Johnston


People also ask

What is array_keys () used for?

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.

How get key of multidimensional array in PHP?

array_keys() returns the keys, numeric and string, from the array . If a search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.

What is In_array function in PHP?

The in_array() function searches an array for a specific value. Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.

How do you check if a key exists in an array PHP?

PHP array_key_exists() Function The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.


2 Answers

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
)
like image 68
user3942918 Avatar answered Nov 14 '22 23:11

user3942918


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.

like image 39
Koushik Das Avatar answered Nov 14 '22 22:11

Koushik Das