How to get last key in an array?

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

<?php

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

Watch a course Learn object oriented PHP

Alternatively, you can use the count() function to get the number of elements in the array, and then use that to index the last element. For example:

<?php

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

Note that both of these methods will modify the internal pointer of the array, so if you need to preserve the state of the array you should use one of these methods instead:

<?php

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

// OR

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

print_r($array);