Getting last 5 elements of a php array

后端 未结 5 1361
清酒与你
清酒与你 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条回答
  •  甜味超标
    2021-01-11 17:10

    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

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

提交回复
热议问题