Getting last 5 elements of a php array

后端 未结 5 1360
清酒与你
清酒与你 2021-01-11 17:04

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

5条回答
  •  梦毁少年i
    2021-01-11 17:14

    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.

提交回复
热议问题