PHP: Get the last element in an associative array.

This is a short guide on how to get the last element (or key) of an associative array in PHP. Note that we will do this without having to loop through the entire array (a wasteful process, I think you’ll agree).

For this tutorial, I’m going to use the following associative array as an example:

$myArray = array(
    'record_1' => 'Example',
    'record_2' => 'Hello',
    'random' => 'Hi' 
);

As you can see, it’s just a simple associative array with three elements. The last element, which has the index “random”, contains the string “Hi”.

To get the last element, we are going to use the PHP function end, which changes theĀ internal pointer of an array to its last element:

<?php

//Our example array.
$myArray = array(
    'record_1' => 'Example',
    'record_2' => 'Hello',
    'random' => 'Hi' 
);

//Set the internal pointer to the end of $myArray.
$lastElement = end($myArray);

//Print it out!
echo $lastElement;

Simple!

But what if we want to get the key / index of the last element? Well, it’s kind of similar:

<?php

//Associative PHP array.
$myArray = array(
    'record_1' => 'Example',
    'record_2' => 'Hello',
    'random' => 'Hi' 
);

//Set the internal pointer to the end.
end($myArray);

//Retrieve the key of the current element.
$key = key($myArray);

//Print it out!
echo $key;

As you can see, using the end function and the key function is a lot less wasteful than looping over the entire array!

Related: Get the first element in an associative array.