How can I get the last 5 elements of a PHP array?
My array is dynamically generated by a MySQL query result. The length is not fixed. If the length is smaller or equ
array_pop()
5 times in a loop? If the returned value is a null
, you've exhausted the array.
$lastFive = array();
for($i=0;$i < 5;$i++)
{
$obj = array_pop($yourArray);
if ($obj == null) break;
$lastFive[] = $obj;
}
After seeing the other answers, I have to admit array_slice()
looks shorter and more readable.