Get the last element of an array in PHP

For getting the last element of an array in PHP you have multiple options, which function slightly differently. The most obvious ones are end(), array_slice() and array_pop().

Getting the last element with end()

The end() function sets the internal pointer of the array to its last element and returns it’s value. It works pretty straight forward, after this function call the array is still intact and you can do with the return value what you’d like; assign it to a variable, print it, e.g.

<?php

$dogs = ['Lassie', 'Hachi', 'Bolt'];

echo end($dogs);
# => 'Bolt'

Getting the last element with array_slice()

With the array_slice() function you extract slices from an existing array. You can use -1 as offset to get just the last item of the array you pass as the first argument. A side note

Be aware that array_slice() returns a new array. So in order to actually get the last element of the original array you need to get the value at index 0 of the return value from array_slice().

<?php

$dogs = ['Lassie', 'Hachi', 'Bolt'];

echo array_slice($dogs, -1)[0];
# => 'Bolt'

Getting the last element with array_pop()

This one functions slightly differently. The array_pop() function removes the last element from an array and returns it. So it works perfectly fine to get the last element of the array, just make sure you also actually meant to remove it from the array.

<?php

$dogs = ['Lassie', 'Hachi', 'Bolt'];

echo array_pop($dogs);
# => 'Bolt'

print_r($dogs);
# => Array
#    (
#        [0] => Lassie
#        [1] => Hachi
#    )

See Also

6 Non-Programming Books for Programmers