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];
source share