Home >Backend Development >PHP Tutorial >How to Filter an Associative Array in PHP Based on Keys from an Indexed Array?
Filtering an Associative Array Based on Keys in an Indexed Array
In PHP, array_filter() provides a convenient method for filtering associative arrays based on their values. However, this function only considers the values, leaving programmers seeking a way to filter keys based on a set of allowed values. This question addresses this challenge.
Given an associative array ($my_array) and an indexed array of allowed keys ($allowed), the task is to remove all keys from $my_array that are not present in $allowed. The desired output is an $my_array containing only the key-value pairs where the keys are found in $allowed.
Solution:
The answer suggests utilizing two array manipulation functions:
Combining these two functions, you can filter the associative array as follows:
$filtered_array = array_intersect_key($my_array, array_flip($allowed));
Here, array_flip($allowed) creates a new array where the values from $allowed become keys, and the keys become values. array_intersect_key($my_array, ...) then compares $my_array with the flipped array, returning an array with only the allowed keys as keys and their associated values.
Example:
Using the provided example:
$my_array = array("foo" => 1, "hello" => "world"); $allowed = array("foo", "bar");
The resulting $filtered_array would be:
array("foo" => 1);
The above is the detailed content of How to Filter an Associative Array in PHP Based on Keys from an Indexed Array?. For more information, please follow other related articles on the PHP Chinese website!