We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
When working with PHP arrays, you often need to filter out specific keys to get a subset of the original array. Whether you’re processing user data, working with API responses, or just tidying up an array, filtering by keys can be a useful technique to simplify and streamline your data.
In this post, we’ll cover an effective way to filter an array based on a set of desired keys. We’ll also explore a few different methods to achieve this, depending on your use case.
Scenario: Filtering an array by a list of keys
Let's say you have an array $data
with various user details, but you only need certain fields, such as name
and city
. Instead of manually pulling out these values, we’ll leverage PHP’s array functions to quickly create a filtered array.
Example Data
$data = [
'name' => 'Alice',
'age' => 25,
'city' => 'New York',
'email' => 'alice@example.com'
];
$allowedKeys = ['name', 'city'];
In this example, $data
holds information about a user, but we only want to keep the name
and city
keys, ignoring the rest.
Solution 1: array_intersect_key
The array_intersect_key
function in PHP is perfect for this scenario. It compares the keys of one array with another and returns a new array containing only the keys present in both.
Here’s how to filter $data
using array_intersect_key
and array_flip
:
$filteredData = array_intersect_key($data, array_flip($allowedKeys));
print_r($filteredData);
How it works
- Flipping the Keys: We first use
array_flip
on$allowedKeys
. This turns the list of allowed keys into an associative array with the keys as values. Soarray_flip($allowedKeys)
will look like:
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.