PHP array_key_last() Function

What is PHP array_key_last() Function?

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

Syntax:

array_last_key(array)

Parameters:

The Function has 1 required parameter-

  • array (Required): The input array.

Return Values:

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

Examples:

Example 1: indexed array

<?php
$languages = ["Zero","One","Two"];
$lastKey = array_key_last($languages);
echo "Last element key is: $lastKey";
?>

Output:

Last element key is: 2

Example 2: For associative array

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

Output:

Last element key is: Third

Example 3:

<?php
$languages = [];
$lastKey = array_key_last($languages);
echo "Last element key is: "; var_dump($lastKey);
?>

Output:

Last element key is: NULL

Example 4:

<?php
$languages = ["Zero","One","Two"];
end($languages);
$lastKey = key($languages);
echo "Last element key is: $lastKey";
?>

Output:

Last element key is: 2

Alternative to array_key_last() Function:

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

Caution:

As you can see the end() + 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_last() function was introduced in PHP 7.3.0 version.

PHP Version Support:

PHP 7 >= 7.3.0, PHP 8

Summary: PHP array_key_last() Function

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

Reference:

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