Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split array into two arrays by index even or odd

Tags:

arrays

php

split

I have this array:

$array = array(a, b, c, d, e, f, g);

I want to split it in two arrays depending if the index is even or odd, like this:

$odd = array(a, c, e, g);

$even = array(b, d, f);

Thanks in advance!

like image 264
Marc Vidal Moreno Avatar asked Sep 13 '12 11:09

Marc Vidal Moreno


People also ask

How do you split an array into two?

To divide an array into two, we need at least three array variables. We shall take an array with continuous numbers and then shall store the values of it into two different variables based on even and odd values.

Which method is used to split two arrays?

We use array_split() for splitting arrays, we pass it the array we want to split and the number of splits.


2 Answers

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;
    }
}
like image 153
Jon Avatar answered Oct 17 '22 06:10

Jon


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);
like image 45
Gareth Avatar answered Oct 17 '22 07:10

Gareth