Filter array - odd even

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

foreach($arr as $key => $value) if($key&1) unset($arr[$key]);

The above removes odd number positions from the array, to remove even number positions, use the following:

Instead if($key&1) you can use if(!($key&1))


Here's a "hax" solution:

Use array_filter in combination with an "isodd" function.

array_filter seems only to work on values, so you can first array_flip and then use array_filter.

array_flip(array_filter(array_flip($data), create_function('$a','return $a%2;')))

Tags:

Php

Arrays