How to filter an array by a condition

How to filter an array by a condition

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Filtering Arrays in PHP: Preserving Keys with array_filter

You have an associative array where you need to retain specific values while discarding others, and crucially, you must preserve the original keys. Given the input ["a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2], the goal is to produce a result containing only the entries where the value equals 2.

The most direct and idiomatic solution in modern PHP is the built-in array_filter() function. This function is designed specifically for this purpose: it iterates over an array and returns a new array containing only the elements that pass a callback test.

To implement this, you pass your original array and a closure (anonymous function) to the filter. Inside that closure, you define the condition—checking if $key or $value meets your criteria. In this specific scenario, since the logic depends entirely on the value, the callback looks like this:

$data = ["a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2];

$filtered = array_filter($data, function ($value) {
    return $value === 2;
});

When you run this code, $filtered will contain ["a" => 2, "c" => 2, "f" => 2]. You will notice that the keys "a", "c", and "f" are preserved exactly as they appeared in the source array. This behavior is guaranteed by array_filter() when used with an associative array; it does not reindex the resulting array like some other languages might with their filter functions.

However, there is a significant pitfall to be aware of regarding default behavior. In PHP 5.x and early PHP 7 versions, array_filter() had a second parameter named $use_keys. By default, this was true, which is exactly what we want here. However, if you ever pass the second argument explicitly as false (or if you are using an older version of PHP where the default behavior might be misremembered), the function will discard keys and return a numerically indexed array: [0 => 2, 1 => 2, 2 => 2].

To ensure your code remains robust across different environments or if refactoring later, it is best practice to explicitly set this flag. You can force the preservation of keys by passing true as the second argument:

$filtered = array_filter($data, function ($value) {
    return $value === 2;
}, ARRAY_FILTER_USE_BOTH | \FILTER_INCLUDE_ZERO); // Note: Standard usage usually relies on default flags.
// Actually, the simpler and safer explicit approach is just relying on the default behavior 
// but being aware of the second argument if ever specified.

// The most robust way to guarantee key preservation in all contexts is simply not passing the second argument 
// unless you explicitly want to change the default, or if you are using a very old PHP version where defaults changed.
// In modern PHP 7.2+, the default for array_filter is to keep keys.

Wait, let's correct that implementation detail. The array_filter() function signature has evolved. The second parameter is not a boolean flag for keeping keys in the way one might expect from older documentation. Instead, the function simply keeps keys by default for associative arrays. The confusion often stems from comparing it to languages like JavaScript where you must specify options.

A more critical nuance involves how you write the callback. You can use ARRAY_FILTER_USE_KEY or ARRAY_FILTER_USE_BOTH flags if your condition requires checking both the key and the value. For instance, if you needed to filter out keys that start with a specific letter while keeping the values, you would change the closure signature:

$filtered = array_filter($data, function ($key, $value) {
    // Condition based on both key and value
    return strlen($key) > 0 && $value === 2;
}, ARRAY_FILTER_USE_BOTH);

Using these flags is essential when your filtering logic isn't purely value-based. If you omit the flag and only need to check the value, array_filter automatically passes just the $value to your closure.

Beyond simple equality checks, array_filter handles complex conditions effortlessly. You could filter based on ranges, string patterns using regular expressions within the callback, or even check external state variables. For example, filtering for values strictly greater than a threshold:

$threshold = 3;
$result = array_filter($data, function ($value) use ($threshold) {
    return $value > $threshold;
});

The resulting array would be ["d" => 5, "e" => 6], again with the original keys intact. This capability makes array_filter a powerful tool for data cleaning without needing to write verbose loops with manual splicing or unset operations.

While Laravel provides many collection helpers that abstract this away (like where()), understanding the underlying PHP function is vital for performance-critical scripts or when working outside the framework. array_filter runs on native C code and is significantly faster than iterating through a Laravel Collection for simple filtering tasks involving large datasets. If you are building a high-performance API endpoint that processes massive logs, sticking to array_filter ensures you aren't introducing unnecessary overhead from object wrapping and collection methods unless you specifically need the collection API's chaining capabilities.

Our network