Video Lesson: Find array elements with callbacks in PHP 8.4

Find array elements with callbacks in PHP 8.4

PHP 8.4 includes some new functions to find elements within arrays, including array_find(), array_find_key(), array_any() and array_all().


Lesson Content

PHP 8.4 introduces several handy array functions that have been missing from the language:

array_find()
array_find_key()
array_any()
array_all()

These functions make it easier to work with arrays when you need to find specific elements within them.

Finding the First Match with array_find()

The array_find() function returns the first element within an array that is returned when its callback returns true:

$codes = [
    'a' => 'alpha',
    'b' => 'beta',
    'c' => 'charlie',
];

$firstMatch = array_find($codes, function(string $value, string $key) {
    return strlen($value) < 5;
});

echo $firstMatch; // 'beta'

Note how within the callback we have access to the current record's value and key.

Getting Just the Key with array_find_key()

The array_find_key() function works just like array_find(), but rather than returning the value, it returns the key:

$codes = [
    'a' => 'alpha',
    'b' => 'beta',
    'c' => 'charlie',
];

$firstMatch = array_find_key($codes, function(string $value, string $key) {
    return strlen($value) < 5;
});

echo $firstMatch; // 'b'

Testing Arrays with array_any() and array_all()

There are a couple other new related functions in PHP 8.4, including array_any() and array_all(). These functions return a boolean though rather than values, which is useful for conditional checks against array matches, similar to JavaScriptโ€™s some() and every() methods.

array_any() returns true if at least one element in the array satisfies the callback condition:

$ages = [25, 31, 42, 17, 28];

$hasMinor = array_any($ages, function(int $age) {
    return $age < 18;
});

var_dump($hasMinor); // bool(true)

array_all() returns true only if all elements in the array meet the condition:

$ages = [25, 31, 42, 17, 28];

$hasMinor = array_all($ages, function(int $age) {
    return $age < 18;
});

var_dump($hasMinor); // bool(false)

If you find yourself writing a lot of foreach loops just to check if some or all items match a condition, these new functions will make your code much cleaner and easier to reason about.

Maggie

Hey, I'm Maggie! ๐Ÿ‘‹

Ask me anything.

Want to chat with Maggie?

Log in for AI tutor access.

Comments

Join the discussion!

Comments

Want to comment on this lesson?

Log in to leave comments.