TheDeveloper
TheDeveloper

Reputation: 940

Foreach loop, show X odd items , then X even items

Below i have a loop that will create two arrays of odd and evens numbers. But what i really need is one loop, that goes through the array and gets first 4 odd items and show them and then show next 4 even items, then next 4 odd item and so on.

<?php       

    $array = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14);
    $odd = array();
    $even = array();
    foreach($array AS $item){
         if ($item & 1) {
            $odd[] = $item ;            
         }else{
            $even[] = $item ;   
         }
    }
?>

i thought having two seprate arrays might make things simpler, but im unsure.

Upvotes: 1

Views: 2311

Answers (1)

Rizier123
Rizier123

Reputation: 59691

This should work for you:

First we get all even values into one array ($even) and all odd values into one array ($odd) with array_filter().

Then we just simply loop through both arrays with array_map(), where we array_chunk() both arrays into groups of 4. In the anonymous function we just simply array_merge() the arrays with the result ($mixed) array.

<?php

        $array = range(1, 14);

        $even = array_filter($array, function($v){
            return $v % 2 == 0;
        });

        $odd = array_filter($array, function($v){
            return $v % 2 == 1;
        });

        $mixed = [];
        array_map(function($v1, $v2)use(&$mixed){
            $mixed = array_merge($mixed, $v1);
            $mixed = array_merge($mixed, $v2);
        }, array_chunk($even, 4), array_chunk($odd, 4));

        print_r($mixed);

?>

Then you can simply loop through your $mixed array. Like this:

foreach($mixed as $v)
    echo $v . "<br>";

output:

2 
4 
6 
8  
1 
3 
5 
7 
10 
12 
14 
9 
11 
13 

Upvotes: 2

Related Questions