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?
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.
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.
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.
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.
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
)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With