First Element of Array by Condition
Finding the first element in a collection that satisfies a specific condition is a common requirement when processing arrays in PHP. The goal is often to stop iterating as soon as the match is found, rather than filtering the entire dataset and then indexing into the result. While standard approaches exist, they often involve verbose chaining of functions or manual loops that obscure intent.
Manual Iteration vs. Functional Approaches
The most direct solution involves a foreach loop where you check the condition inside the body and break immediately upon success. This is technically sound and performs well because it short-circuits the iteration. However, many developers find this imperative style cumbersome when they prefer functional programming patterns.
Consequently, a popular alternative found in community discussions involves combining array_filter with array_values and array access:
$result = [
['value' => 100, 'tag' => 'a'],
['value' => 200, 'tag' => 'b'],
['value' => 300, 'tag' => 'a'],
];
$target = array_values(
array_filter(
$result,
fn($e) => $e['value'] > 199
)
)[0] ?? null;
This approach works but introduces unnecessary overhead. array_filter iterates over the entire input to create a new array of all matching elements, even if only one exists at the beginning. Furthermore, wrapping the result in array_values is strictly necessary only because array_filter preserves keys from the source; it adds a step that feels like syntactic sugar rather than logic. Finally, accessing [0] requires handling the case where no matches exist to avoid fatal errors.
The array_search Pattern with Callbacks
PHP provides a built-in function designed specifically for this scenario: array_search. While often used with strings to find keys, it accepts a callable as its third argument in PHP 5.3 and later (and is the primary use case in modern development). This allows you to search an array using a condition without filtering the whole set first.
$condition = fn($e) => $e['value'] > 199;
$key = array_search(
null,
$result,
true, // Use strict comparison
$condition
);
if ($key !== false) {
$firstMatch = $result[$key];
}
This method is significantly more elegant than the manual loop or the array_filter chain. It returns the key of the first element satisfying the condition, or false if none are found. The underlying implementation stops iterating once the predicate returns true, offering better performance on large datasets where a match appears early. Note that this feature was stabilized in PHP 5.3 but became a standard part of the language's functional capabilities over time.
Handling Edge Cases and Null Safety
Regardless of the method chosen, safety is paramount when accessing array elements. The array_search approach naturally handles the "no match" scenario by returning false, which is distinct from a valid key (since keys are always non-negative integers). This eliminates the need for default values like ?? null unless you explicitly want to convert the failure state into a specific object or default array structure.
If you prefer the functional style without writing an explicit loop, array_find is not part of the PHP core standard library (it exists in extensions like symfony/polyfill-php82 or utility libraries), so relying on it requires external dependencies. For pure PHP, array_search with a callback remains the most robust built-in solution.
When to Use This Pattern
This pattern is particularly useful when you need to validate data or locate specific configuration settings within a list. For example, if you are iterating over a list of user permissions and need the first one that grants access, using array_search keeps your code declarative. You define what you are looking for rather than how to traverse the list.
For teams using the Laravel framework, this pattern aligns well with the language's philosophy of readable, expressive code. If you ever find yourself writing complex loops inside service classes that simply boil down to "find the first match," consider switching to array_search with a callback. It reduces cognitive load and leverages the engine's optimization for early exit conditions.
The choice ultimately depends on your preference between imperative clarity and functional brevity, but understanding that array_filter is not required for this task helps avoid unnecessary complexity in production code.