Question
Given a PHP associative array and an indexed array of allowed key names, how can you remove every key from the associative array that does not appear in the allowed list?
$my_array = array(
"foo" => 1,
"hello" => "world"
);
$allowed = array("foo", "bar");
The desired result is:
$my_array = array(
"foo" => 1
);
Since array_filter() traditionally passes values to its callback, what is the best way to filter the array by its keys?
Short Answer
You will learn how to retain selected keys in a PHP associative array. The primary approach is array_intersect_key() combined with array_flip(), which turns an allowed-value list into a lookup array whose keys can be compared efficiently.
Concept
An associative array stores key-value pairs. In this example, "foo" and "hello" are keys, while 1 and "world" are values.
The task is not to filter based on values. It is to keep a pair only when its key is present in a separate allowed list.
PHP provides array_intersect_key() for this purpose. It compares the keys of one array with the keys of another array and returns matching pairs from the first array.
However, $allowed is an indexed array:
array("foo", "bar")
Here, "foo" and "bar" are values, not keys. array_flip() swaps each value with its key, producing an array suitable for key comparison:
array(
"foo" => 0,
"bar" => 1
)
The numeric values do not matter. Only the keys matter to array_intersect_key().
Mental Model
Think of $my_array as a set of labelled boxes:
- box labelled
foocontains1 - box labelled
hellocontainsworld
$allowed is a guest list containing the labels foo and bar.
To decide which boxes may stay, compare each box label with the guest list. array_flip() turns the guest list into a fast label lookup, and array_intersect_key() keeps only boxes with approved labels.
Syntax and Examples
Use array_intersect_key() to retain key-value pairs whose keys exist in another array.
$filtered = array_intersect_key($source, $allowedKeysAsArray);
When your allowed keys are stored as values in an indexed array, flip them first:
$my_array = array(
"foo" => 1,
"hello" => "world"
);
$allowed = array("foo", "bar");
$my_array = array_intersect_key($my_array, array_flip($allowed));
print_r($my_array);
Output:
Array
(
[foo] => 1
)
array_flip($allowed) creates keys named foo and bar. Then array_intersect_key() checks whether each key in exists in that flipped array.
Step by Step Execution
Consider this code:
$my_array = array("foo" => 1, "hello" => "world");
$allowed = array("foo", "bar");
$allowedLookup = array_flip($allowed);
$result = array_intersect_key($my_array, $allowedLookup);
Step by step:
-
$my_arraycontains these pairs:array("foo" => 1, "hello" => "world") -
array_flip($allowed)converts:array("foo", "bar")into:
array( => , => )
Real World Use Cases
Filtering an associative array by allowed keys is common when handling structured data:
- API request whitelisting: Keep only fields that clients are permitted to update, such as
nameandemail. - Database updates: Remove unexpected input fields before building an update payload.
- Configuration loading: Select only configuration options supported by a component.
- Form processing: Keep expected form fields and discard extra submitted data.
- Data exports: Return only approved fields from a larger record.
For example, an API might receive more fields than it accepts:
$input = array(
"name" => "Ava",
"email" => "ava@example.com",
"is_admin" => true
);
$editableFields = array("name", "email");
$updateData = array_intersect_key($input, array_flip($editableFields));
$updateData cannot contain is_admin, because it is not on the allowed list.
Real Codebase Usage
In real PHP applications, this pattern is often called whitelisting fields. A whitelist is safer than trying to list every field that should be removed, because new unexpected fields are automatically excluded.
A common pattern is to place the allowed names in a reusable list:
$allowedFields = array("title", "body", "published_at");
$allowedLookup = array_flip($allowedFields);
$cleanInput = array_intersect_key($_POST, $allowedLookup);
For repeated filtering, create $allowedLookup once rather than calling array_flip() every time:
$allowedLookup = array_flip(array("name", "email"));
$firstUser = array_intersect_key($firstInput, $allowedLookup);
$secondUser = array_intersect_key($secondInput, $allowedLookup);
Filtering allowed fields is not complete validation. After selecting fields, validate their types, formats, and business rules. For example, an allowed field may still be missing or invalid.
Common Mistakes
Comparing against the wrong array keys
This does not work as intended because $allowed has numeric keys (0, 1), not foo and bar:
// Incorrect
$result = array_intersect_key($my_array, $allowed);
Fix it by flipping the allowed values into keys:
$result = array_intersect_key($my_array, array_flip($allowed));
Using array_intersect()
array_intersect() compares values, so it would compare 1 and "world" against "foo" and "bar".
= (, );
Comparisons
| Tool | Compares | Best use |
|---|---|---|
array_intersect_key() | Keys | Keep pairs whose keys exist in another array |
array_intersect() | Values | Keep values that appear in another array |
array_diff_key() | Keys | Remove pairs whose keys exist in another array |
array_filter() | Usually values; keys can be enabled in modern PHP | Apply custom rules with a callback |
If you already have an allowed-key lookup array, no flip is needed:
$allowedLookup = array(
"foo" => true,
"bar" => true
);
$result = array_intersect_key(, );
Cheat Sheet
// Keep only keys listed in $allowed
$result = array_intersect_key($source, array_flip($allowed));
// Example
$source = array("foo" => 1, "hello" => "world");
$allowed = array("foo", "bar");
$result = array_intersect_key($source, array_flip($allowed));
// array("foo" => 1)
- Use
array_intersect_key()for key matching. - Use
array_intersect()for value matching. array_flip()converts allowed values into lookup keys.- Assign the returned array to keep the result.
- Values passed to
array_flip()must be strings or integers. - Use
array_diff_key()when you want the inverse: remove known keys.
FAQ
Why does array_intersect_key() need array_flip()?
array_intersect_key() compares array keys. An indexed allowed list stores names as values, so array_flip() turns those names into keys.
Does array_intersect_key() modify the original array?
No. It returns a new filtered array. Assign the return value back to the original variable if needed.
Can I use array_filter() to filter by key in PHP?
Yes, in PHP 5.6 and later, use the ARRAY_FILTER_USE_KEY flag. For a simple whitelist, array_intersect_key() is usually more direct.
What happens if no keys are allowed?
The result is an empty array, which is a normal outcome.
Are key comparisons case-sensitive?
Yes. foo and Foo are different array keys.
Can the allowed list contain integer keys?
Yes. array_flip() accepts integer and string values. Be aware that PHP may convert numeric-looking string keys to integers in array-key contexts.
How do I remove allowed keys instead of keeping them?
Use :
Mini Project
Description
Build a small function that prepares a safe profile-update payload. It receives incoming user data and keeps only fields that the application explicitly permits. This mirrors a common API or form-handling task.
Goal
Create a function that filters profile input to the allowed name, email, and bio fields.
Requirements
Create an associative array containing both allowed and unexpected profile fields.
Create an indexed array listing the allowed field names.
Use array_intersect_key() and array_flip() to keep only allowed fields.
Store the filtered result in a separate variable.
Display the final filtered array.
Keep learning
Related questions
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.