What is the array_key_first method in PHP?

The array_key_first method can be used to get the first key of an array.

Syntax

array_key_first(array $array): int|string|null

If the passed array doesn’t have any elements, then it returns null.

Example

<?php
$arr = [
'ONE' => 1,
'TWO' => 2,
'THREE' => 3
];
$firstKey = array_key_first($arr);
echo "The first key of the array is :". $firstKey;
?>

In the code above, we create an array and get the first key of the array using the array_key_first method.

Example 2

Let’s call array_key_first on an empty array.

<?php
$arr = [];
$firstKey = array_key_first($arr);
var_dump($firstKey);
?>

In the code above, we will get NULL as a result because the passed array is empty.

Free Resources