How to get the value of the last key in an array

6 Oct
2008

Very often I find myself wanting to get only the value of the last key in an array. I used to do

sizeof($array);

to find out the number of total elements, so I knew the position of the last value. Today I ran into a much easier way to select it.

With the following line of code you can set the desired last value to a variable:

$variable = array_pop($array);

For more info and some useful examples check out the PHP manual.

Feel free to share:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • LinkedIn
  • StumbleUpon
  • Technorati

2 Responses to How to get the value of the last key in an array

Avatar

Ruud Altenburg

August 27th, 2010 at 13:12

This is an option only if you want to immediately delete that item from the array. Why not use end() instead?

Avatar

Coen Coppens

August 29th, 2010 at 22:23

Very nice addition to the post! I wasn’t aware of the existence of this function. It’s definitely a better way of getting the last value. Thank you for your reply (-:

Comment Form

top