Home >Backend Development >PHP Tutorial >How Can I Preserve Keys When Filtering an Array in PHP?

How Can I Preserve Keys When Filtering an Array in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-17 07:54:25838browse

How Can I Preserve Keys When Filtering an Array in PHP?

Preserving Keys in Array Filtering Using array_intersect_key and array_flip

In PHP, the array_filter() function can be used to remove elements from an array based on a custom callback function. However, the callback only receives the values of the array, not the keys.

Consider the scenario where you have an associative array ($my_array) and a list of allowed keys in an indexed array ($allowed). The goal is to filter $my_array and remove all keys that are not present in $allowed.

The most effective approach is to leverage the array_intersect_key and array_flip functions. The array_intersect_key function filters an array key-value pairs based on the keys present in another array. The array_flip function flips the keys and values of an array, effectively creating a mapping between values and keys.

By combining these functions, you can achieve the desired filtering:

$filtered_array = array_intersect_key($my_array, array_flip($allowed));

This code will create a new array ($filtered_array) that contains only the key-value pairs from $my_array where the keys are present in $allowed. The result will be identical to the desired output:

array(
  ["foo"] => 1
)

The above is the detailed content of How Can I Preserve Keys When Filtering an Array in PHP?. 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