PHP array_key_first() Function

What is PHP array_key_first() Function?

If you want to get first key of an array, use array_key_first() function. The function doesn’t modify the internal pointer.

Syntax:

array_first_key(array)

Parameters:

The Function has 1 required parameter-

  • array (Required): The input array.

Return Values:

  • It returns the key of first element.
  • If the input array is empty, the function returns NULL. See example 3.

Examples:

Example 1: indexed array

<?php
$languages = ["Zero","One","Two"];
$firstKey = array_key_first($languages);
echo "First element key is: $firstKey";
?>

Output:

First element key is: 0

Example 2: For associative array

<?php
$languages = ["First"=>"PHP", "Second" => "Python", "Third" => "Flutter"];
$firstKey = array_key_first($languages);
echo "First element key is: $firstKey";
?>

Output:

First element key is: First

Example 3:

<?php
$languages = [];
$firstKey = array_key_first($languages);
echo "First element key is: "; var_dump($firstKey);
?>

Output:

First element key is: NULL

Example 4:

<?php
$languages = ["First"=>"PHP", "Second" => "Python", "Third" => "Flutter"];
reset($languages);
$firstKey = key($languages);
echo "First element key is: $firstKey";
?>

Output:

First element key is: First

Alternative to array_key_first() Function:

Alternative to the array_key_first() function is using both reset() function and key() function together. Look at the example 4. The reset() function sets the internal pointer of an array to its first element and then, the key() function retrieve the key of that element.

Caution:

As you can see the reset() + key() method changes internal pointer’s location which is the drawback of this method. Prior to PHP 7.3.0 version, the above was an alternative. So, use this method in your own risk. The array_key_first() function was introduced in PHP 7.3.0 version.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP array_key_first() Function

The array_key_first() function is a built-in PHP function and part of the PHP’s array functions. It is the preferable way to retrieve first key of an array.

Reference:

https://www.php.net/manual/en/function.array-key-first.php