Keeping even numbered elements of an array?

Assuming numeric keys:

foreach ($array as $key => $value) {
    if ($key % 2 != 0) {
        unset($array[$key]);
    }
}

EDIT

Here goes my slightly more insane solution which keeps the index continuous without re-indexing. ;o)

foreach ($array as $key => $value) {
    if (!($key%2)) {
        $array[$key/2] = $value;
    }
}
$array = array_slice($array, 0, ceil(count($array)/2));

<?php
$x = range('a', 'f');

$x = array_map('array_shift', 
       array_chunk($x, 2)
     );

var_dump($x);

or another one

<?php
class ArrayEvenIterator extends ArrayIterator {
    public function next() {
        parent::next();
        return parent::next();
    }
}

$x = range('a', 'f');
$x = iterator_to_array(new ArrayEvenIterator( $x ), false);

var_dump($x);

or with a php 5.3 closure (which isn't better than global in this case ;-) )

<?php
$x = range('a', 'f');

$x = array_filter( $x, function($e) use(&$c) { return 0===$c++%2; });

var_dump($x);

Tags:

Php

Arrays