How to get last key in an array in PHP

→ Are you a new visitor? Please visit the page guidance for new visitors ←

How to get last key in an array in PHP?

Arrays can have lots of elements, some that may not be needed at one point. Let’s say that we need in some cases the last key or last element of an array in PHP, what would you do?

A very good solution and clever practice would be the following one:

1st solution (clever)

You would use the end() function to move the pointer directly at the bottom of the array. That way you can have access directly to the last element.

  • end()¬†advances array ‘s internal pointer to the last element, and returns its value.
  • key()¬†returns the index element of the current array position.

The above example will output:

 2nd solution (faster)

This would also work and is bit more faster. We are using array_slice() function for getting only the last element of the array.

Both solutions are good and can be used with confidence in your own projects.

Request an article ←