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
I just want to extend the question a little bit. What if you looping though a big file and want to keep the last 5 lines or 5 elements from a current position. And you don't want to keep huge array in a memory and having problems with the performance of array_slice.
This is a class that implements ArrayAccess interface.
It gets array and desired buffer limit.
You can work with the class object like it's an array but it will automatically keep ONLY 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];
You need array_slice, which does exactly this.
$items = array_slice($items, -5);
-5
means "start at five elements before the end of the array".
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.
array_slice($array, -5)
should do the trick
It's simple use array_slice and count()
$arraylength=count($array);
if($arraylength >5)
$output_array= array_slice($array,($arraylength-5),$arraylength);
else
$output_array=$array;