PHP

PHP 8.4 Array Inspection Functions

PHP 8.4 will come with four new array functions that enable and simplify inspection. Let’s dive in and take a look the benefits.

This is the second post in our PHP 8.4 themed series. You can read all about another feature, property hooks, here.

array_find

array_find($array, $callback) returns the first match (truthy) value that your callback returns.

function is_prime(int $number): bool {
if ($number == 1) {
return false;
}
for ($i = 2; $i <= sqrt($number); $i++) {
if ($number % $i == 0) {
return false;
}
}
return true;
}

array_find([1, 2, 3, 4, 5], is_prime);
// 2

There are actually two parameters that get passed to the callback, $value and $key, in that order, so in the above example we only rely upon an array’s iteration value. We could also filter by an associative array like so:

function is_foo(mixed $value, str: key): bool {
return $key === "foo";
}

array_find([
"fruit" => "apple",
"name" => "Joe Smith",
"foo" => "bar"
], is_foo);
// "bar"

array_find_key

Much like array_find, array_key_find inspects your array to return the first match. The difference being instead of returning the first value, you’ll get the first key.

function is_bar(mixed $value): bool {
return $value === "bar";
}

array_find_key([
"fruit" => "apple",
"name" => "Joe Smith",
"foo" => "bar"
], is_bar);
// "foo"

array_all

array_all() works much like all() in Python, it returns a boolean based on whether all elements in your array return true in your callback function.

function is_even(int $number): bool {
return $number % 2 === 0;
}

array_all([2, 4, 6], is_even);
// true

array_all([2, 4, 5], is_even);
// false

array_all(
["a" => 1, "b" => 2, "c" => 3],
fn($v, $k) => is_numeric($v)
);
// true

array_all(
[1 => 1, "b" => 2, 4 => 3],
fn($v, $k) => !is_numeric($k)
);
// false

array_any

This will return true if any of the elements in the array match, as distinct from array_all where all must.

function is_even(int $number): bool {
return $number % 2 === 0;
}

array_any([2, 4, 6], is_even);
// true

array_any([2, 4, 5], is_even);
// true

array_any([1, 3, 5], is_even);
// false

array_any(
["a" => 1, "b" => 2, "c" => 3],
fn($v, $k) => is_numeric($v)
);
// true

array_any(
[1 => 1, "b" => 2, 4 => 3],
fn($v, $k) => !is_numeric($k)
);
// true

Final thoughts

Whilst it’s always nice to have helper functions, these don’t really do anything that array_map or array_filter already provide from a surface level perspective. Furthermore, a great many projects will have one or more of these function names to provide something resembling these implementations, making it a bit of a problem for the completely understandable and natural task of updating your PHP version. As long as this doesn’t apply to you and your projects, these functions can be a great addition to your toolbelt.

Read the RFC documentation at https://wiki.php.net/rfc/array_find.