PHP Function Reference

PHP array_key_last() Function



The PHP array_key_last() function returns the last key of the given array without affecting the internal array pointer.

Syntax

array_key_last(array)

Parameters

array Required. Specify an array.

Return Value

Returns the last key of array if the array is not empty; null otherwise.

Exceptions

NA.

Example:

The example below shows the usage of array_key_last() function.

<?php
$Arr = array("Red" => 1, 
             "Green" => 2, 
             "Blue" => 3);

//printing all keys of the array using
//array_key_last and array_pop functions
$n = sizeof($Arr);
for($i = 0; $i < $n; $i++) {
  //displaying last element
  echo array_key_last($Arr)."\n";

  //popping last element
  array_pop($Arr);  
}
?>

The output of the above code will be:

Blue
Green
Red

Example:

Consider one more example where the array_key_last() function is used with an index array.

<?php
$Arr = array_fill(-2, 5, 10);
print_r($Arr);

echo "\n";
//displaying the last key (last index)
echo "Last index: ".array_key_last($Arr);
?>

The output of the above code will be:

Array
(
    [-2] => 10
    [-1] => 10
    [0] => 10
    [1] => 10
    [2] => 10
)

Last index: 2

❮ PHP Array Reference