Stop Using array_filter to Find One Item

Stop Using array_filter to Find One Item

T

Theodoros Kafantaris

Δημοσιεύτηκε στις 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.

Μοιραστείτε το άρθρο

Προκαλέστε το Μυαλό Σας

NEW!

Κάντε ένα διάλειμμα από το διάβασμα και δοκιμάστε τις ικανότητές σας στη λογική με τον ημερήσιο γρίφο μας!

Τελευταία Πρόκληση: Jul 9, 2026

Daily Logic Ladder - July 9, 2026

Παίξτε τον Σημερινό Γρίφο

Σχετικά με το Blog Μας

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

Ⓒ 2026. Με επιφύλαξη παντός δικαιώματος atomic