Home > Backend Development > PHP Tutorial > How Can I Filter Associative Array Keys Based on Indexed Array Values in PHP?

How Can I Filter Associative Array Keys Based on Indexed Array Values in PHP?

DDD
Release: 2024-12-13 11:52:10
Original
755 people have browsed it

How Can I Filter Associative Array Keys Based on Indexed Array Values in PHP?

Filter Associative Array Keys Based on Indexed Array Values

Many programmers encounter the challenge of selectively filtering out keys from an associative array based on specific values stored in an indexed array. In PHP, the array_filter() callback function only provides access to array values, leaving out the key-matching functionality.

Consider the following scenario where $my_array contains key-value pairs:

$my_array = ["foo" => 1, "hello" => "world"];
Copy after login

And $allowed is a simple indexed array with allowed keys:

$allowed = ["foo", "bar"];
Copy after login

The goal is to modify $my_array such that it only contains keys that are also present in $allowed. The desired output is:

$my_array = ["foo" => 1];
Copy after login

To achieve this, we can leverage the array_intersect_key() and array_flip() functions:

var_dump(array_intersect_key($my_array, array_flip($allowed)));
Copy after login

Explanation:

  • **array_flip($allowed)**: Reverses the keys and values of $allowed, converting it to an associative array where the original keys become values and vice versa. This allows us to compare keys from $my_array to values in the flipped array.
  • array_intersect_key($my_array, $reversed): Intersects the keys of $my_array with the flipped $allowed array. This retains only the keys from $my_array that are present as values in the flipped array, effectively filtering out undesired keys.

By combining these functions, we can selectively remove keys from the associative array based on values in the indexed array without manually iterating through the keys and comparing them.

The above is the detailed content of How Can I Filter Associative Array Keys Based on Indexed Array Values in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template