rfc:array_find

This is an old revision of the document!


PHP RFC: array_find

Introduction

This RFC proposes the addition of a new function array_find, which returns the first element for which a predicate callback returns true.

There are currently lots of functions in PHP for modifying or filtering arrays. However, there is no simple function to search an array with a function and return the first result. Implementing this in userland is relatively simple (either via a loop or via array_filter combined with reset), but the function is often required, so this type of function is often built [1]. I therefore see a reason to include this function as standard with the next PHP version. In addition, the implementation of the function is similar to array_filter and relatively trivial to implement, so the maintenance effort should be low.

Proposal

Add a new function array_find:

function array_find(array $array, callable $callback, bool $return_array_key = false): mixed {}

Parameters

array $array

The array that should be searched.

callable $callback

The callback function to use to search the array. The function is passed two parameters. The first parameter contains the array value. The second parameter contains the array index.

bool $return_array_key

If this parameter is true, the array key is returned instead of the value.

Return Value

The function returns the first entry for which the $callback returns true. If the third parameter ($return_array_key) is true, the function returns the array index. Otherwise the function returns the corresponding array value. If no matching entry is found, the function returns NULL

Examples

$array = [
    'dog',
    'cat',
    'cow',
    'duck',
    'goose',
    'elephant'
];
 
// Find the first animal with a name longer than 4 characters.
var_dump(array_find($array, function (string $value) {
    return strlen($value) > 4;
})); // string(5) "goose"

Backward Incompatible Changes

Functions created by the user and named array_find lead to a PHP error with the new version.

Proposed PHP Version(s)

PHP 8.4

RFC Impact

To SAPIs

None.

To Existing Extensions

None.

To Opcache

None.

New Constants

None.

php.ini Defaults

None.

Open Issues

None.

Unaffected PHP Functionality

This RFC only adds a new function to PHP and only affects previously defined functions which are named as the proposed function.

Implementation

References

[1] GitHub currently has 656 results for array_find and Laravel implements this feature by default with array_first.

rfc/array_find.1712494950.txt.gz · Last modified: 2024/04/07 13:02 by josh