New functions for searching in an array. Writing from scratch

New array functions are planned for PHP 8.4: array_find, array_find_key, array_any и array_allwhich are helper functions for common patterns of checking an array for elements that match a certain condition.

There are currently several functions that process arrays using callbacks. However, there are still missing functions to find a single element that matches a condition and the closely related functions to check if elements match a condition. These functions are relatively easy to implement in a user environment, but they are often required, which leads to the wheel being reinvented over and over again. In addition, these types of functions are also implemented in other programming languages ​​such as Rust, JavaScript or C++. Therefore, there is a reason to include these functions as standard in the next version of PHP. In addition, the implementation of these functions is very similar to array_filter and is relatively easy to implement, so maintenance costs should be low.

array_find

array_find returns the value of the first element for which the function $callback returns value true. If the matching element is not found, the function returns the value NULL.

function array_find(array $array, callable $callback): mixed {
    foreach ($array as $key => $value) {
        if ($callback($value, $key)) {
            return $value;
        }
    }
 
    return null;
}

Let's look at how this function works using examples.

$array = [
    'a' => 'dog',
    'b' => 'cat',
    'c' => 'cow',
    'd' => 'duck',
    'e' => 'goose',
    'f' => 'elephant'
];
 
// Поиск первого животного с именем, длина которого превышает 4 символа.
var_dump(array_find($array, function (string $value) {
    return strlen($value) > 4;
})); // string(5) "goose"
 
// Поиск первого животного с именем, которое начинается на f.
var_dump(array_find($array, function (string $value) {
    return str_starts_with($value, 'f');
})); // NULL
 
// Поиск первого животного, в котором ключ массива является первым символом животного.
var_dump(array_find($array, function (string $value, $key) {
   return $value[0] === $key;
})); // string(3) "cow"
 
// Поиск первого животного, у которого ключ массива соответствует регулярному выражению.
var_dump(array_find($array, function ($value, $key) {
   return preg_match('/^([a-f])$/', $key);
})); // string(3) "dog"

array_find_key

array_find_key returns the key of the first element for which the function $callback returns value true. If the matching element is not found, the function returns the value NULL.

function array_find_key(array $array, callable $callback): mixed {
    foreach ($array as $key => $value) {
        if ($callback($value, $key)) {
            return $key;
        }
    }
 
    return null;
}

Let's look at how this function works using examples.

$array = [
    'a' => 'dog',
    'b' => 'cat',
    'c' => 'cow',
    'd' => 'duck',
    'e' => 'goose',
    'f' => 'elephant'
];
 
// Поиск первого животного с именем, длина которого превышает 4 символа.
var_dump(array_find_key($array, function (string $value) {
    return strlen($value) > 4;
})); // string(1) "e"
 
// Поиск первого животного с именем, которое начинается на f.
var_dump(array_find_key($array, function (string $value) {
    return str_starts_with($value, 'f');
})); // NULL
 
// Поиск первого животного, в котором ключ массива является первым символом животного.
var_dump(array_find_key($array, function (string $value, $key) {
   return $value[0] === $key;
})); // string(1) "c"
 
// Поиск первого животного, у которого ключ массива соответствует регулярному выражению.
var_dump(array_find_key($array, function (string $value, $key) {
   return preg_match('/^([a-f])$/', $key);
})); // string(1) "a"

array_any

array_any returns value trueIf $callback returns value true for any element. Otherwise, the function returns the value false.

function array_any(array $array, callable $callback): bool {
    foreach ($array as $key => $value) {
        if ($callback($value, $key)) {
            return true;
        }
    }
 
    return false;
}

Let's look at how this function works using examples.

$array = [
    'a' => 'dog',
    'b' => 'cat',
    'c' => 'cow',
    'd' => 'duck',
    'e' => 'goose',
    'f' => 'elephant'
];
 
// Проверяет, не содержит ли название какого-либо животного более 5 букв.
var_dump(array_any($array, function (string $value) {
    return strlen($value) > 5;
})); // bool(true)
 
// Проверяет, не содержит ли название какого-либо животного более 3 букв.
var_dump(array_any($array, function (string $value) {
    return strlen($value) < 3;
})); // bool(false)
 
// Проверяет, не является ли какой-либо ключ массива строкой.
var_dump(array_any($array, function (string $value, $key) {
   return !is_string($key);
})); // bool(false)

array_all

array_all returns value trueIf $callback returns value true for all elements. Otherwise, the function returns the value false.

function array_all(array $array, callable $callback): bool {
    foreach ($array as $key => $value) {
        if (!$callback($value, $key)) {
            return false;
        }
    }
 
    return true;
}

Let's look at how this function works using examples.

$array = [
    'a' => 'dog',
    'b' => 'cat',
    'c' => 'cow',
    'd' => 'duck',
    'e' => 'goose',
    'f' => 'elephant'
];
 
// Проверяет, все ли названия животных короче 12 букв.
var_dump(array_all($array, function (string $value) {
    return strlen($value) < 12;
})); // bool(true)
 
// Проверяет, все ли названия животных длиннее 5 букв.
var_dump(array_all($array, function (string $value) {
    return strlen($value) > 5;
})); // bool(false)
 
// Проверяет, все ли ключи массива являются строками.
var_dump(array_all($array, function (string $value, $key) {
   return is_string($key);
})); // bool(true)

The usefulness of these methods is obvious, but let's look at how many times these functions have been written by people themselves.

Functions created by the user and named array_find, array_find_key, array_any or array_allresult in a PHP error in the new version. A quick search on GitHub shows that there is 656 resultsdefining the array_find symbol, 28 resultsdefining the array_find_key symbol, 127 resultsdefining the array_any symbol and 284 resultswhich define the array_all symbol for the PHP language.

Looking at the search results, I estimate that about 30% of those results are functions that are not in a namespace, not part of a class, and are false positives (eg symbol – db_array_all instead of array_all).

More interesting news, thoughts and memes in Fir DEV

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *