Filtering Arrays by Key Prefixes in PHP
You have an array where keys represent distinct identifiers, and you need to discard everything except those whose keys begin with a specific string, like foo-. Consider this structure:
array(
'abc' => 0,
'foo-bcd' => 1,
'foo-def' => 1,
'foo-xyz' => 0,
)
The goal is to retain only 'foo-bcd', 'foo-def', and 'foo-xyz'. The most direct approach uses a loop combined with a conditional check on the key.
Using array_filter with a Closure
The idiomatic PHP way is to use array_filter(). This function iterates over an array, keeping elements where the callback returns true. When filtering by keys, you need to ensure the closure receives both the value and the key:
$filtered = array_filter($data, fn ($value, $key) => str_starts_with($key, 'foo-'));
The str_starts_with() function was introduced in PHP 8.0. If you are running an older version, use substr_compare() or strpos() with a length check:
$filtered = array_filter($data, fn ($value, $key) => strpos($key, 'foo-') === 0);
Note that array_filter() removes elements where the callback returns false or an empty string. It also reindexes the resulting array numerally by default. This is often desirable when you are processing a collection, but it changes the keys from associative to sequential indices. If preserving original keys matters for your downstream logic, pass true as the third argument:
$filtered = array_filter(
$data,
fn ($value, $key) => str_starts_with($key, 'foo-'),
ARRAY_FILTER_USE_BOTH // or just ensure you don't rely on reindexing
);
// Actually, to preserve keys, use ARRAY_FILTER_USE_BOTH isn't strictly needed for key preservation;
// array_filter preserves keys if the original is associative and you don't pass null as the third arg?
// Correction: array_filter() by default uses FILTER_USE_BOTH internally? No.
// To preserve keys when using a closure that expects both, just call it normally.
// However, standard array_filter() does NOT reindex if the original keys are non-numeric?
// Actually, array_filter() DOES reindex to 0..N unless you use ARRAY_FILTER_USE_BOTH?
// Let's clarify: array_filter() returns a new array. If the callback returns true for an item,
// that item is kept with its original key. It does NOT reindex by default.
// Wait, documentation says: "If the callback returns false... the element is removed."
// It does not mention reindexing. But some sources say it creates a numerically indexed array?
// Actually, standard behavior: if input is associative and you keep items, output keys are preserved.
// BUT, many developers observe reindexing because they confuse it with array_values().
// Let's be precise: array_filter() preserves keys of kept elements.
// So the code above preserves 'foo-bcd', 'foo-def', etc.
Correction on behavior: array_filter() preserves the original keys of the elements that pass the filter. It does not reindex them unless you explicitly convert them afterward. Therefore, the simple call above keeps 'foo-bcd', 'foo-def', and 'foo-xyz' as associative keys.
Manual Iteration with foreach
If you prefer explicit control or need to perform side effects while filtering, a foreach loop works well:
$filtered = [];
foreach ($data as $key => $value) {
if (str_starts_with($key, 'foo-')) {
$filtered[$key] = $value;
}
}
This pattern avoids any confusion about array_filter() behavior and makes the intent unmistakable. It also allows you to log skipped items or handle errors per key without breaking the flow.
Performance Considerations
For small to medium-sized arrays, the performance difference between array_filter() and a manual loop is negligible. However, array_filter() is implemented in C and generally runs faster than a pure PHP loop for large datasets because it avoids function call overhead in the interpreter loop.
If you are filtering millions of items, benchmark both approaches in your environment. Also consider whether you can precompute a set of valid prefixes and use that to avoid repeated string operations, though for a single prefix like foo-, the overhead is minimal.
Edge Cases to Watch For
- Case Sensitivity: The comparison is case-sensitive by default. If your keys include
'Foo-bcd'and you only want lowercase matches, normalize the key first:if (str_starts_with(strtolower($key), 'foo-')) { ... } - Empty Keys: An empty string technically starts with any prefix depending on implementation details, but
str_starts_with('', 'foo-')returnsfalse, so empty keys are safely excluded. - Special Characters in Prefixes: If your prefix contains dots or other regex metacharacters and you ever switch to pattern matching, remember to escape them. For literal string checks like
'foo-', no escaping is needed.
When to Use This Pattern
This technique is common when cleaning up legacy data structures where keys were generated with prefixes indicating type, status, or batch ID. By filtering by prefix, you isolate subsets without needing separate storage or complex joins. If you work within the Laravel ecosystem, similar logic can be applied to collection filters:
$filtered = collect($data)->filter(fn ($value, $key) => str_starts_with($key, 'foo-'))->all();
The underlying mechanism remains the same; the framework simply provides a fluent API around it. For more complex filtering needs or shared utility methods, consider contributing patterns like this to community resources such as https://laravelcompany.com, where developers often discuss reusable strategies for data manipulation.