PHP array_key_last() function
The array_key_last () function in PHP gets the last key of an array if the specified array is not empty.
Syntax
array_key_last ( array $array )
Parameter
array(required)- This parameter signifies the input array.
Return
This function returns the last key of the specified array if the array is not empty else it returns NULL.
Example 1
$array = ['first' => 1, 'second' => 2, 'third' => 3,'fourth' => 4];
echo("Array : \n");
var_export($array);
//will return the last key for $array
$lastKey = array_key_last($array);
//printing the returned value
echo("\nThe last key of the array is ");
var_dump($lastKey);
?>
Output
Array : array ( 'first' => 1, 'second' => 2, 'third' => 3, 'fourth' => 4, ) The last key of the array is string(6) "fourth"
Example 2
96, 'Harshit' => 94, 'Sapna' => 93];
echo("Student Array : \n");
var_export($contestent_array);
//will return the last key for $array
$lastKey = array_key_last($contestent_array);
//printing the returned value
echo("\nThe II runner up is ");
var_dump($lastKey);
//removing the last element of the array
array_pop($contestent_array);
echo("\nThe I runner up is ");
var_dump(array_key_last($contestent_array));
//removing the last element of the array
array_pop($contestent_array);
echo("\nThe winner of the match is ");
var_dump(array_key_last($contestent_array));
?>
Output
Student Array: array ( 'Reema' => 96, 'Harshit' => 94, 'Sapna' => 93, ) The II runner up is string(5) "Sapna" The I runner up is string(7) "Harshit" The winner of the match is string(5) "Reema"
Example 3
Output
Array: 'The first key of the array is 0'
Example 4
'Reema',1 => 'Harshit',2 =>'Sapna'];
echo("Student Array : \n");
var_export($array);
//will return the last key for $array
$lastKey = array_key_last($array);
//printing the returned value
echo("\nThe last element is ");
var_dump($lastKey);
//adding elements at the end of the array
array_push($array,"Amar","Sukla");
echo("\nNew Array: ");
var_export($array);
echo("\nThe last element is ".array_key_last($array));
?>
Output
Student Array : array ( 0 => 'Reema', 1 => 'Harshit', 2 => 'Sapna', ) The last element is int(2) New Array: array ( 0 => 'Reema', 1 => 'Harshit', 2 => 'Sapna', 3 => 'Amar', 4 => 'Sukla', ) The last element is 4
