php.net

(PHP 8 >= 8.5.0)

array_firstGets the first value of an array

Description

function array_first(array $array): mixed

Get the first value of the given array.

Parameters

array
An array.

Return Values

Returns the first value of array if the array is not empty; null otherwise.

Examples

Example #1 Basic array_first() Usage

<?php
$array = [1 => 'a', 0 => 'b', 3 => 'c', 2 => 'd'];
$firstValue = array_first($array);
var_dump($firstValue);
?>

The above example will output:

string(1) "a"

See Also

5

sunny_reitgassl at hotmail dot de

4 months ago

For PHP < 8.5.0 && >= 7.3.0:
if (! function_exists("array_first")) {
    function array_first(array $array) {
        return $array ? $array[array_key_first($array)] : null;
    }
}

0

firejox at gmail dot com

3 months ago

There is another Polyfill for PHP < 8.5
<?php
if (!function_exists("array_first")) {
    function array_first(array $array) {
        if (!empty($array)) return current(array_slice($array, 0, 1));
        return null;
    }
}
?>

Read the original on php.net ↗