Filter Associative Array Keys Based on Indexed Array Values
Many programmers encounter the challenge of selectively filtering out keys from an associative array based on specific values stored in an indexed array. In PHP, the array_filter() callback function only provides access to array values, leaving out the key-matching functionality.
Consider the following scenario where $my_array contains key-value pairs:
$my_array = ["foo" => 1, "hello" => "world"];
And $allowed is a simple indexed array with allowed keys:
$allowed = ["foo", "bar"];
The goal is to modify $my_array such that it only contains keys that are also present in $allowed. The desired output is:
$my_array = ["foo" => 1];
To achieve this, we can leverage the array_intersect_key() and array_flip() functions:
var_dump(array_intersect_key($my_array, array_flip($allowed)));
Explanation:
By combining these functions, we can selectively remove keys from the associative array based on values in the indexed array without manually iterating through the keys and comparing them.
The above is the detailed content of How Can I Filter Associative Array Keys Based on Indexed Array Values in PHP?. For more information, please follow other related articles on the PHP Chinese website!