Split array into two arrays by index even or odd

One solution, using anonymous functions and array_walk:

$odd = array();
$even = array();
$both = array(&$even, &$odd);
array_walk($array, function($v, $k) use ($both) { $both[$k % 2][] = $v; });

This separates the items in just one pass over the array, but it’s a bit on the “cleverish” side. It’s not really any better than the classic, more verbose

$odd = array();
$even = array();
foreach ($array as $k => $v) {
    if ($k % 2 == 0) {
        $even[] = $v;
    }
    else {
        $odd[] = $v;
    }
}

Leave a Comment