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

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-13 08:39:10386browse

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:

  • array_intersect_key(): This function performs a comparison between two arrays using their keys. It returns a new array containing only keys that are present in both arrays.
  • array_flip(): This function flips the keys and values of an associative array, effectively turning its keys into values and vice versa.

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!

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