Question

Filter Associative Array Keys with an Allowed List in PHP

phparrayskeyfilteringwhitelist

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 foo contains 1
  • box labelled hello contains world

$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.

Take Quiz

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 $my_array exists in that flipped array.

array_intersect_key() returns a new array; it does not change $my_array unless you assign the result back to it.

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:

  1. $my_array contains these pairs:

    array("foo" => 1, "hello" => "world")
    
  2. array_flip($allowed) converts:

    array("foo", "bar")
    

    into:

    array("foo" => 0, "bar" => 1)
    
  3. array_intersect_key() checks keys from $my_array:

    • foo exists in $allowedLookup, so "foo" => 1 is kept.
    • hello does not exist in $allowedLookup, so it is removed.
  4. $result becomes:

    array("foo" => 1)
    

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 name and email.
  • 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.

Take Quiz

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 email 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".

// Incorrect: compares values, not keys
$result = array_intersect($my_array, $allowed);

Use array_intersect_key() when the decision is based on keys.

Forgetting to assign the returned array

Most PHP array functions return a new array.

// The result is discarded
array_intersect_key($my_array, array_flip($allowed));

Assign it back if you want to replace the original variable:

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

Using array_flip() with unsupported values

array_flip() can flip only integer and string values. Do not use it directly on an allowed list containing arrays, objects, or booleans.

// Problematic: arrays cannot become PHP array keys
$allowed = array(array("foo"));

Keep allowed key names as strings or integers.

Confusing an empty result with an error

If none of the source keys are allowed, the valid result is an empty array:

array()

Comparisons

ToolComparesBest use
array_intersect_key()KeysKeep pairs whose keys exist in another array
array_intersect()ValuesKeep values that appear in another array
array_diff_key()KeysRemove pairs whose keys exist in another array
array_filter()Usually values; keys can be enabled in modern PHPApply 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($my_array, $allowedLookup);

In PHP 5.6 and later, array_filter() can pass keys by using ARRAY_FILTER_USE_KEY:

$result = array_filter(
    $my_array,
    function ($key) use ($allowed) {
        return in_array($key, $allowed, true);
    },
    ARRAY_FILTER_USE_KEY
);

This is useful for custom conditions, but array_intersect_key() plus array_flip() is clearer for a simple allowed-key list.

Take Quiz

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 array_diff_key():

$result = array_diff_key($my_array, array_flip($allowed));
Take Quiz

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.

Take Quiz

Keep learning

Related questions

View more