Filter a 2d array to only keep rows with a specified value in a specified column

Filter a 2d array to only keep rows with a specified value in a specified column

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

Stefan Bogdanescu

Founder & Senior Architect

Filtering Multidimensional Arrays Without Recursion

Filtering a multidimensional array to isolate rows containing specific key-value pairs is a common task, but the approach depends heavily on your data structure. The source query suggests a desire for a "recursive" solution because the depth of the array is unknown. However, in many practical scenarios, especially when dealing with tabular data or list items like the example provided, recursion isn't actually necessary if you can define the scope of your search.

Consider the specific use case where you have an indexed array containing associative arrays:

$arr = [
    ['id' => 1, 'name' => 'cat 1'],
    ['id' => 2, 'name' => 'cat 2'],
    ['id' => 3, 'name' => 'cat 1']
];

If the goal is strictly to filter this top-level collection where every element is a single row of data, you do not need to write a recursive function. You simply need to iterate through the array and check the condition for each sub-array. In PHP, array_filter is the idiomatic tool for this. It accepts a callback that returns true if an element should be kept.

Here is how you implement it:

$keyToSearch = 'name';
$valueToMatch = 'cat 1';

$filtered = array_filter($arr, function ($row) use ($keyToSearch, $valueToMatch) {
    return isset($row[$keyToSearch]) && $row[$keyToSearch] === $valueToMatch;
});

// Re-index keys if a sequential index is required
$filtered = array_values($filtered);

This approach is O(n), meaning it scans the array exactly once. It is fast, readable, and avoids the overhead of function call stacks associated with recursion. The trade-off here is that this method assumes the "rows" you are filtering are at the immediate top level of $arr. If your data structure nests these rows inside other arrays (e.g., ['items' => [...]]), a simple flat filter won't reach them.

That is where the misconception about recursion often arises. If the depth is truly unknown and nested structures are arbitrary, you must traverse the entire tree of arrays. In PHP, there is no built-in function for deep traversal. You have two main options: write a custom recursive helper or use RecursiveIteratorIterator.

A custom recursive solution is often preferred for its readability when the logic inside each node is complex. The pattern involves checking if a value exists at the current level and then recursively processing any child arrays (typically indexed by keys like 'children', 'items', or simply iterating over all values if the structure is flat-but-nested).

function findMatches(array $data, string $key, mixed $value): array {
    $matches = [];

    foreach ($data as $item) {
        // Check if current item matches
        if (isset($item[$key]) && $item[$key] === $value) {
            $matches[] = $item;
        }

        // Recurse into child arrays if they exist and are arrays themselves
        foreach ($item as $child) {
            if (is_array($child)) {
                $matches = array_merge($matches, findMatches($child, $key, $value));
            }
        }
    }

    return $matches;
}

The logic here is sound: you check the current node, then flatten the results of searching every nested sub-array. This handles "deep" arrays without needing to know the depth beforehand.

However, if performance becomes a bottleneck with massive datasets, this recursive approach can hit PHP's recursion limit (XDEBUG_INFO or memory_limit). In such cases, converting the structure into an iterator or using a stack-based iterative approach is safer. But for most standard filtering tasks involving lists of objects or rows, the flat array_filter combined with array_values to re-index keys is the most efficient and maintainable solution.

If you are building this within a Laravel application, ensure you are leveraging collection methods when possible, as they handle key re-indexing automatically via filter(). For raw array manipulation outside of a framework context, the explicit callback pattern ensures clarity on exactly which keys are being inspected.

Our network