Are there any functions in PHP that help find out all the keys with the same value in an associative array? For example, there is an array as follows:
$data1 = array("Peter" => "1", "Ann" => "1", "Susan" => "2", "Tom"=> "3");
I only want the keys with the value "1" (ie Peter and Ann). Thanks for help.
You can use array_keys
with the optional second parameter:
array_keys()
returns the keys, numeric and string, from the array.If the optional
search_value
is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.
Use array_intersect and array_keys.
$data1 = array("Peter" => "1", "Ann" => "1", "Susan" => "2", "Tom"=> "3");
$find = 1;
Var_dump(array_keys(array_intersect($data1, [$find])));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.