W3docs

How to get last key in an array?

You can use the end() function to get the last element of an array in PHP.

The recommended way to get the last key of an array in PHP (7.3+) is using the array_key_last() function. For example:

How to get the last key of an array in PHP?

<?php

$array = [1, 2, 3, 4, 5];
$last_key = array_key_last($array);
echo $last_key; // Outputs 4

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

Alternatively, you can use the end() function combined with key() to get the last key. Note that end() modifies the internal pointer of the array. For example:

How to get the last key of an array in PHP using end() and key()?

<?php

$array = [1, 2, 3, 4, 5];
end($array);
$last_key = key($array);
echo $last_key; // Outputs 4

If you need to preserve the state of the array after using end(), you can reset the pointer:

How to get the last key of an array in PHP while preserving the array state?

<?php

$array = [1, 2, 3, 4, 5];
end($array);
$last_key = key($array);
reset($array);

print_r($array);

You can also use the count() function to calculate the last index, but this only works for sequential numeric arrays. For associative arrays, it will produce incorrect results. For example:

How to get the last key of an array in PHP using count() function?

<?php

$array = [1, 2, 3, 4, 5];
$last_key = count($array) - 1;
echo $last_key; // Outputs 4