Stop Using array_filter to Find One Item

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.

T Theodoros Kafantaris December 06, 2025 1 min read
Stop Using array_filter to Find One Item

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:

Code
                    $users = [...];

// Inefficient: Filters ALL users, creates new array, then gets first.
$admin = reset(array_filter($users, fn($u) => $u->role === 'admin'));
                

The Modern Way:

Code
                    $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?

  1. Performance: It stops looping the moment it finds a match.

  2. Readability: The intent of the code is immediately clear.

Share this post

Back to Blog

Let's talk

Stay Curious. Stay Inspired.

Join our community of thinkers, developers, and lifelong learners. Explore ideas that challenge and inspire you to think differently.