Split array into two arrays by index even or odd

Use array_filter (PHP >= 5.6):

$odd = array_filter($array, function ($input) {return $input & 1;}, ARRAY_FILTER_USE_KEY);
$even = array_filter($array, function ($input) {return !($input & 1);}, ARRAY_FILTER_USE_KEY);

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

Tags:

Php

Arrays

Split