Tips 02/01/2026 2 min read

Stop Using array_filter: Meet PHP's Native array_find()

B
Beartropy Team
hace 17 horas

For years, if you wanted to find the first element in an array that matched a condition without using Laravel Collections, you had to write awkward, inefficient code.

With PHP 8.4, we finally have a dedicated, native function for this: array_find().

The Old Way (Inefficient)

Previously, to find a specific user in a raw array, you likely filtered the whole list and then grabbed the first result:

1$users = [
2 ['id' => 1, 'role' => 'dev'],
3 ['id' => 2, 'role' => 'admin'],
4 ['id' => 3, 'role' => 'dev'],
5];
6 
7// ❌ Bad: Filters the ENTIRE array, creating a copy in memory
8$admin = array_values(array_filter($users, fn($u) => $u['role'] === 'admin'))[0] ?? null;

This is not only verbose but computationally wasteful. It iterates through every single item even after it finds the match.

The New Way (PHP 8.4+)

Now, you can use array_find(), which stops execution immediately after finding the first match and returns the value directly.

1// ✅ Clean, fast, and readable
2$admin = array_find($users, fn($u) => $u['role'] === 'admin');

Bonus: Need the Key?

If you need the index instead of the value, PHP 8.4 also introduced array_find_key():

1$adminIndex = array_find_key($users, fn($u) => $u['role'] === 'admin');
2// Returns: 1

While Laravel Collections are powerful, using native functions where possible reduces overhead and dependency complexity in utility classes.

Tags

#php #php-8-4 #clean-code #arrays

Share this post