PHPKonf Istanbul PHP Conference 2019 - Call for Papers

array_key_first

(PHP 7 >= 7.3.0)

array_key_firstGets the first key of an array

Description

mixed array_key_first ( array $array )

Get the first key of the given array without affecting the internal array pointer.

Parameters

array

An array.

Return Values

Returns the first key of array if the array is not empty; NULL otherwise.

Examples

Example #1 Basic array_key_first() Usage

<?php
$array 
= ['a' => 1'b' => 2'c' => 3];

$firstKey array_key_first($array);

var_dump($firstKey);
?>

The above example will output:

string(1) "a"

See Also

  • array_key_last() - Gets the last key of an array
  • reset() - Set the internal pointer of an array to its first element
add a note add a note

User Contributed Notes 2 notes

up
9
mail at vitalyart dot ru
1 month ago
For PHP < 7.3.0:

<?php
if (!function_exists('array_key_first')) {
   
/**
     * Gets the first key of an array
     *
     * @param array $array
     * @return mixed
     */
   
function array_key_first(array $array)
    {
        if (
count($array)) {
           
reset($array);
            return
key($array);
        }

        return
null;
    }
}

echo
array_key_first([
   
'foo' => 'value1',
   
'bar' => 'value2',
]);

// Output: foo
up
-4
@manzoorwanijk
1 month ago
For PHP < 7.3.0 :

<?php
if ( ! function_exists( 'array_key_first' ) ) {
   
/**
     * Polyfill for array_key_first() function added in PHP 7.3.
     *
     * Get the first key of the given array without affecting
     * the internal array pointer.
     *
     * @param mixed $array An array
     *
     * @return mixed The first key of array if the array is not empty; NULL otherwise.
     */
   
function array_key_first( $array ) {
       
$key = null;

        if (
is_array( $array ) ) {

            foreach (
$array as $key => $value ) {
                break;
            }
        }

        return
$key;
    }
}
?>
To Top