PHP 8.4 array_any and array_find, in real code
My Drupal import code used to be full of the same little loop: walk an array, set a $found = FALSE flag, break on the first hit, return the flag. It works, but every one of those loops is four to six lines of ceremony around a single question. PHP 8.4 added three functions that answer those questions directly, and after a few weeks of using them I've mostly stopped writing the flag version.
The three functions, as documented
According to the manual (array_find, array_any, array_all), all three have the same shape: (array $array, callable $callback), and the callback receives $value and $key. They differ in what they return:
array_find()returns the first value for which the callback returnstrue, ornullif none match.array_any()returnstrueif at least one element matches.array_all()returnstrueonly if every element matches.
All three stop calling the callback as soon as the answer is known, just like a break would. They were added in PHP 8.4.0.
Recipe 1: "is this row complete?"
Importing a CSV, I want to skip rows with a blank required column. The old version looped over the required column names and returned early. Now it's one expression:
<?php
declare(strict_types=1);
final class RowValidator {
private const REQUIRED = ['email', 'name', 'country'];
/**
* Checks that every required column has a non-blank value.
*
* @param array<string, mixed> $row
* One parsed CSV row, keyed by column name.
*/
public function isComplete(array $row): bool {
return array_all(
self::REQUIRED,
fn (string $column): bool => trim((string) ($row[$column] ?? '')) !== '',
);
}
}
I iterate over the list of required names, not over the row, so a column that is missing entirely fails the check through the ?? fallback. Trace it with ['email' => 'a@b.be', 'name' => ' ']: email passes, name trims to an empty string and fails, so array_all() returns false and never even looks at country.
Recipe 2: role checks and "first match" lookups
Drupal accounts expose getRoles(), which returns a plain list of role IDs. "Does this user have any editor-ish role?" is exactly an array_any() question:
<?php
use Drupal\Core\Session\AccountInterface;
function mymodule_is_editorial(AccountInterface $account): bool {
return array_any(
$account->getRoles(),
fn (string $rid): bool => str_starts_with($rid, 'editor_'),
);
}
/**
* Returns the first contact flagged as primary, or NULL.
*
* @param array<int, array<string, mixed>> $contacts
*/
function mymodule_primary_contact(array $contacts): ?array {
return array_find(
$contacts,
fn (array $contact): bool => !empty($contact['primary']),
);
}
Nothing clever, and that's the point: the intent is readable at a glance, and there's no mutable flag variable for the next person to misread.
Two gotchas I hit
The null ambiguity. array_find() returns null when nothing matches, so if null is a legitimate element you can't tell "found a null" from "found nothing". The manual's user notes point to array_find_key() for that case, since a key can't be null. For arrays of arrays or objects, as above, it's a non-issue.
The callback always gets two arguments. Because the key is passed too, handing a single-argument built-in like is_int straight in can throw an ArgumentCountError (again per the manual's notes). Wrap it in an arrow function and the problem disappears.
Also remember these take arrays, not generators, so for a lazy stream you still want a foreach with an early return. And array_all() on an empty array is vacuously true: if "no rows" should be an error, check for it separately before you trust the result. Short of that, I'd happily replace every flag-and-break loop in a codebase that's already on 8.4 with these three.