Filter array - odd even

后端 未结 7 2062
别那么骄傲
别那么骄傲 2021-01-12 05:56

How can a filter out the array entries with an odd or even index number?

Array
(
    [0] => string1
    [1] => string2
    [2] => string3
    [3] =&         


        
7条回答
  •  攒了一身酷
    2021-01-12 06:32

    You could also use SPL FilterIterator like this:

    class IndexFilter extends FilterIterator {
        public function __construct (array $data) {
            parent::__construct(new ArrayIterator($data));
        }   
    
        public function accept () {
            # return even keys only
            return !($this->key() % 2);
        }     
    }
    
    $arr      = array('string1', 'string2', 'string3', 'string4');
    $filtered = array();
    
    foreach (new IndexFilter($arr) as $key => $value) {
        $filtered[$key] = $value;
    }
    
    print_r($filtered);
    

提交回复
热议问题