PHP - How to get odd/even numbers from an array into two separate arrays

2467 views php
8

I have a PHP array like so:

$posts = array(1,2,3,4,5,6,7,8,9); 

What I would like to do is separate the values into two separate arrays, one with the odd numbers and one with the even numbers like so:

$evenposts = array(2,4,6,8);
$oddposts = array(1,3,5,7,9);

I haven't attempted anything to achieve this as I'm really not sure where to start. Any help would be much appreciated!

answered question

" haven't attempted anything to achieve this as I'm really not sure where to start" -> A loop.

@treyBake not that dupe. OP wants odd/even values, not keys

@Cid see here for code: phpfiddle.tk/b57bb1f1 <- doesn't run for some reason, locally it produces OP requirements though

[1,2,3,4,5,6,7,8,9]; is an example, it could contain anything else. If you go with [0,1,2,3,4,5,6,7,8,9]; this won't work

@Cid while the question is not exactly same the only difference in answer is that the value is going to be compared in condition instead of key.

@Cid that's because that code uses $k instead of $v phpfiddle.tk/4952f8cc

1 Answer

9

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

Source: Split array into two arrays by index even or odd

posted this

Have an answer?

JD

Please login first before posting an answer.