JesusValera

New PHP 8.4 array functions

array_find, array_find_key, array_all & array_any

 Found a typo? Edit me

The PHP 8.4 version includes four new array functions that will help to write more clear and concise code.

interlaken-mountain

Let's take a look at the current PHP array_* methods and an small example about how to deal with each of them (similarly as I did in this JavaScript post).

Imperative vs Declarative

There are two ways of applying transformations to arrays in PHP.

Example: Having a list of numbers from 1 to 10, to filter odd numbers, we can do:

$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

## Imperative
$result = [];
foreach ($numbers as $n) {
    if ($n % 2 === 1) {
        $result[] = $n;
    }
}

## Declarative
$result = array_filter($numbers, fn (int $n) => $n % 2 === 1);

As you can see, in the declarative way, we did not create any explicit loop or added any if statement, it was all done automatically under-the-hood, we just defined which condition should be applied to each element of the list.

There is no a better way, both imperative and declarative codes do the same, in some situations one way could fit better than the other, although, usually the declarative is shorter and cleaner.

Declarative functions

Before PHP 8.4, we have numerous PHP functions, eg:

Since PHP 8.4 we have the new following methods:

The new four methods were discussed in this RFC.

New functions

array_find 🔎

array_find() is useful to get the value of the first occurrence of a certain element in an array. It will return NULL otherwise.

$countries = ['Spain', 'Germany', 'Portugal', 'France'];
$find = array_find($countries, fn(string $c) => str_contains($c, 'an'));
var_dump($find);

*** OUTPUT ***
string(7) "Germany"

array_find_key 🔑

array_find_key() is useful to get the key of the first occurrence of a certain element in an array. It will return NULL otherwise.

$countries = ['Spain', 'Germany', 'Portugal', 'France'];
$findKey = array_find_key($countries, fn(string $c) => str_contains($c, 'an'));
var_dump($findKey);

*** OUTPUT ***
int(1)

array_all ☘️

array_all() is useful to know if all elements from an array meet a specific closure. This method will return true or false.

$countries = ['Spain', 'Germany', 'Portugal', 'France'];
$allA = array_all($countries, fn(string $c) => str_contains($c, 'a'));
$allE = array_all($countries, fn(string $c) => str_contains($c, 'e'));
var_dump($allA);
var_dump($allE);

*** OUTPUT ***
bool(true)
bool(false)

array_any 🧵

array_any() is useful to know if any element from an array meet a specific closure. This method will return true or false.

$countries = ['Spain', 'Germany', 'Portugal', 'France'];
$anyA = array_any($countries, fn(string $c) => str_contains($c, 'a'));
$anyE = array_any($countries, fn(string $c) => str_contains($c, 'e'));
var_dump($anyA);
var_dump($anyE);

*** OUTPUT ***
bool(true)
bool(true)