Movatterモバイル変換


[0]ホーム

URL:


    array_first »
    « array_find

    array_find_key

    (PHP 8 >= 8.4.0)

    array_find_keyReturns the key of the first element satisfying a callback function

    Description

    array_find_key(array$array,callable$callback):mixed

    array_find_key() returns the key of the first element of anarray for which the givencallback returnstrue. If no matching element is found the function returnsnull.

    Parameters

    array
    Thearray that should be searched.
    callback

    The callback function to call to check each element, which must be

    callback(mixed$value,mixed$key):bool
    If this function returnstrue, the key is returned fromarray_find_key() and the callback will not be called for further elements.

    Return Values

    The function returns the key of the first element for which thecallback returnstrue. If no matching element is found the function returnsnull.

    Examples

    Example #1array_find_key() example

    <?php
    $array
    = [
    'a'=>'dog',
    'b'=>'cat',
    'c'=>'cow',
    'd'=>'duck',
    'e'=>'goose',
    'f'=>'elephant'
    ];

    // Find the first animal with a name longer than 4 characters.
    var_dump(array_find_key($array, function (string $value) {
    return
    strlen($value) >4;
    }));

    // Find the first animal whose name begins with f.
    var_dump(array_find_key($array, function (string $value) {
    return
    str_starts_with($value,'f');
    }));

    // Find the first animal where the array key is the first symbol of the animal.
    var_dump(array_find_key($array, function (string $value,$key) {
    return
    $value[0] ===$key;
    }));

    // Find the first animal where the array key matching a RegEx.
    var_dump(array_find_key($array, function ($value,$key) {
    return
    preg_match('/^([a-f])$/',$key);
    }));
    ?>

    The above example will output:

    string(1) "e"NULLstring(1) "c"string(1) "a"

    See Also

    • array_find() - Returns the first element satisfying a callback function
    • array_all() - Checks if all array elements satisfy a callback function
    • array_any() - Checks if at least one array element satisfies a callback function
    • array_filter() - Filters elements of an array using a callback function
    • array_reduce() - Iteratively reduce the array to a single value using a callback function

    Found A Problem?

    Learn How To Improve This PageSubmit a Pull RequestReport a Bug
    add a note

    User Contributed Notes

    There are no user contributed notes for this page.
    To Top
    and to navigate •Enter to select •Esc to close •/ to open
    PressEnter without selection to search using Google

    [8]ページ先頭

    ©2009-2025 Movatter.jp