Home >Backend Development >PHP Tutorial >How to Filter an Associative Array Based on Keys Found in an Indexed Array?

How to Filter an Associative Array Based on Keys Found in an Indexed Array?

Linda Hamilton
Linda HamiltonOriginal
2024-12-24 02:44:14615browse

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:

  1. Use array_intersect_key to compare the keys of $my_array with the values of $allowed. This is made possible by the array_flip function, which exchanges the keys and values of an array.
  2. The resulting array will only include keys from $my_array that are also present in $allowed.
$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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn