Stop Using array_filter to Find One Item
Theodoros Kafantaris
Published on December 06, 2025
How often do you need to find just the first matching item in an array? Historically, developers used array_filter (which loops through everything) and then grabbed the reset() or current() item. It was messy and inefficient.
Modern PHP finally introduces array_find.
The Old Way:
$users = [...];
// Inefficient: Filters ALL users, creates new array, then gets first.
$admin = reset(array_filter($users, fn($u) => $u->role === 'admin'));
The Modern Way:
$users = [...];
// Efficient: Stops as soon as it finds the match. Returns object or null.
$admin = array_find($users, fn($u) => $u->role === 'admin');
if ($admin) {
// Do something
}
Why use it?
-
Performance: It stops looping the moment it finds a match.
-
Readability: The intent of the code is immediately clear.