Stop Using array_filter to Find One Item

Stop Using array_filter to Find One Item

T

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:

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

Challenge Your Mind

NEW!

Take a break from reading and test your logic skills with our daily puzzle!

Latest Challenge: Dec 7, 2025

Daily Logic Ladder - Jean-Jacques Rousseau

Play Today's Puzzle

About Our Blog

Explore where technology meets intellect. From technical tutorials to intellectual exploration—stay curious and inspired.

â’¸ 2025. All rights reserved by atomic