sólo quiero extender la pregunta un poco. ¿Qué ocurre si bucles en un archivo grande y desea mantener las últimas 5 líneas o 5 elementos de una posición actual? Y no desea mantener un gran conjunto en una memoria y tener problemas con el rendimiento de array_slice.
Esta es una clase que implementa la interfaz ArrayAccess.
Obtiene la matriz y el límite de buffer deseado.
se puede trabajar con la clase de objeto como si fuera un array pero mantendrá automáticamente sólo 5 últimos elementos
<?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];
Por favor, mostrar en el código, la matriz generada dinámicamente que no tiene longitud. –