Getting last 5 elements of php array

How can I get the last 5 elements of a PHP array.

The array is dynamically generated by the result of the MySQL query. the length is not fixed. If length <= 5, then get all the others last 5.

I tried with a PHP function like last() and array_pop() , but they only give the last element.

Please help me solve the problem.

+6
source share
5 answers

You need array_slice , which does just that.

 $items = array_slice($items, -5); 

-5 means "start with five elements to the end of the array."

+19
source

array_pop() 5 times in a loop? If the return value is null , you have exhausted the array.

 $lastFive = array(); for($i=0;$i < 5;$i++) { $obj = array_pop($yourArray); if ($obj == null) break; $lastFive[] = $obj; } 

After looking at the other answers, I have to admit that array_slice() looks shorter and more readable.

+5
source

array_slice ($array, -5) should do the trick

+3
source

Simple use of array_slice and count()

 $arraylength=count($array); if($arraylength >5) $output_array= array_slice($array,($arraylength-5),$arraylength); else $output_array=$array; 
0
source

I just want to expand the question a bit. What to do if you loop a large file and want to save the last 5 lines or 5 elements from the current position. And you do not want to store a huge array in memory and have array_slice performance problems.

This is a class that implements the ArrayAccess interface.

It gets the array and the desired buffer.

You can work with the class object like an array, but it will automatically save ONLY the last 5 elements

 <?php class MyBuffer implements ArrayAccess { private $container; private $limit; function __construct($myArray = array(), $limit = 5){ $this->container = $myArray; $this->limit = $limit; } public function offsetSet($offset, $value) { if (is_null($offset)) { $this->container[] = $value; } else { $this->container[$offset] = $value; } $this->adjust(); } public function offsetExists($offset) { return isset($this->container[$offset]); } public function offsetUnset($offset) { unset($this->container[$offset]); } public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } public function __get($offset){ return isset($this->container[$offset]) ? $this->container[$offset] : null; } private function adjust(){ if(count($this->container) == $this->limit+1){ $this->container = array_slice($this->container, 1,$this->limit); } } } $buf = new MyBuffer(); $buf[]=1; $buf[]=2; $buf[]=3; $buf[]=4; $buf[]=5; $buf[]=6; echo print_r($buf, true); $buf[]=7; echo print_r($buf, true); echo "\n"; echo $buf[4]; 
0
source

Source: https://habr.com/ru/post/910719/


All Articles