Get the Last Key of an Array in PHP

In PHP, there are several ways to retrieve the last key of an array, depending on your specific use case and the version of PHP you are using. In this tutorial, we'll explore different methods to accomplish this task.

1. Using end() and key()

One of the simplest ways to get the last key of an array is by using the end() and key() functions. Here's how you can do it:

<?php
// Sample array
$fruits = array(
    "apple" => "red",
    "banana" => "yellow",
    "cherry" => "red",
    "date" => "brown"
);

// Move the internal pointer to the end of the array
end($fruits);

// Get the key of the current element (which is now the last element)
$lastKey = key($fruits);

// Output the last key
echo "The last key is: " . $lastKey;
?>

In this example, we first use end() to move the internal array pointer to the last element, and then we use key() to retrieve the key of the last element.

2. Using array_slice() to get Array Last Key

Another way to get the last key of an array is by using array_slice(). Here's an example:

<?php
// Sample array
$fruits = array(
    "apple" => "red",
    "banana" => "yellow",
    "cherry" => "red",
    "date" => "brown"
);

// Get the last element of the array using array_slice
$lastElement = array_slice($fruits, -1, 1, true);

// Extract the key of the last element
$lastKey = key($lastElement);

// Output the last key
echo "The last key is: " . $lastKey;
?>

In this example, we use array_slice() to extract the last element of the array and then use key() to retrieve its key. The true parameter in array_slice() ensures that the keys are preserved in the result.

3. Using array_keys() and end()

You can also use array_keys() along with end() to get the last key. Here's how:

<?php
// Sample array
$fruits = array(
    "apple" => "red",
    "banana" => "yellow",
    "cherry" => "red",
    "date" => "brown"
);

// Get an array of keys
$keys = array_keys($fruits);

// Get the last key from the array of keys
$lastKey = end($keys);

// Output the last key
echo "The last key is: " . $lastKey;
?>

In this example, we first use array_keys() to get an array of all keys and then use end() to retrieve the last key from that array.

4. Using PHP 7.3+ Syntax to get Last Key of array

Starting from PHP 7.3, you can also use the array_key_last() function to directly get the last key of an array:

<?php
// Sample array
$fruits = array(
    "apple" => "red",
    "banana" => "yellow",
    "cherry" => "red",
    "date" => "brown"
);

// Get the last key using array_key_last()
$lastKey = array_key_last($fruits);

// Output the last key
echo "The last key is: " . $lastKey;
?>

This method is the most straightforward and concise way to get the last key in PHP 7.3 and later.

Choose the method that best suits your code and PHP version, and you'll be able to easily retrieve the last key of an array in PHP.