Home >Backend Development >PHP Tutorial >How to Filter an Associative Array Based on Keys Found in an Indexed Array?
Checking Associative Array Keys Against Indexed Array Values
Filtering an associative array by comparing its keys with values from an indexed array can be a challenge, as the callback function in array_filter() only provides access to values. However, there's a solution using a combination of array_intersect_key and array_flip.
Consider the following scenario:
$my_array = ["foo" => 1, "hello" => "world"]; $allowed = ["foo", "bar"];
Our goal is to exclude any keys in $my_array that are not found in $allowed, resulting in the desired output:
$my_array = ["foo" => 1];
Solution with array_intersect_key and array_flip:
$filtered_array = array_intersect_key($my_array, array_flip($allowed));
Output:
var_dump($filtered_array); array(1) { ["foo"]=> int(1) }
The above is the detailed content of How to Filter an Associative Array Based on Keys Found in an Indexed Array?. For more information, please follow other related articles on the PHP Chinese website!