How Can I Preserve Keys When Filtering an Array in PHP?
Dec 17, 2024 am 07:54 AMPreserving 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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

11 Best PHP URL Shortener Scripts (Free and Premium)

Working with Flash Session Data in Laravel

6 Extra Skills Every PHP Developer Should Have

Simplified HTTP Response Mocking in Laravel Tests

Build a React App With a Laravel Back End: Part 2, React

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

12 Best PHP Chat Scripts on CodeCanyon
