New PHP 8.4 array functions
array_find, array_find_key, array_all & array_any
Found a typo? Edit meThe PHP 8.4 version includes four new array functions that will help to write more clear and concise code.
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.
- While in imperative way we tell step by step how to get,
- in the declarative we tell not how to do it, but what we want
Example: Having a list of numbers from 1 to 10, to filter odd numbers, we can do:
$numbers = ;
## Imperative
$result = ;
foreach {
if {
$result = $n;
}
}
## Declarative
$result = ;
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:
array_map(?callable $callback, array $array, array ...$arrays): array
¶array_walk(array|object &$array, callable $callback, mixed $arg = null): true
¶array_filter(array $array, ?callable $callback = null, int $mode = 0): array
¶array_reduce(array $array, callable $callback, mixed $initial = null): mixed
¶array_key_exists(string|int|float|bool|resource|null $key, array $array): bool
¶in_array(mixed $needle, array $haystack, bool $strict = false): bool
¶
Since PHP 8.4 we have the new following methods:
array_find(array $array, callable $callback): mixed
¶array_find_key(array|object &$array, callable $callback, mixed $arg = null): true
¶array_all(array $array, ?callable $callback = null, int $mode = 0): array
¶array_any(array $array, callable $callback, mixed $initial = null): mixed
¶
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 = ;
$find = ;
;
*** OUTPUT ***
string ""
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 = ;
$findKey = ;
;
*** OUTPUT ***
int
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 = ;
$allA = ;
$allE = ;
;
;
*** OUTPUT ***
bool
bool
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 = ;
$anyA = ;
$anyE = ;
;
;
*** OUTPUT ***
bool
bool