How to split array into two arrays based on even or odd position

02nd, January 2018 By

To split array into two array based on event or odd position you need to to find out the even or odd key by traversing all the elements in the array. For example:

 <?php
 $dd=array(); // declared first array
 $dd[0]='first';
 $dd[1]='second';
 $dd[2]='third';
 $dd[3]='fourth';

 $mydd =array(); // second array that will contain even index element
 $mydd1=array(); // second array that will contain odd index element
 foreach($dd as $key=>$val)
 {
 if(($key==0)||($key%2==0)) // it will give element which are at even index.
 {
 $mydd[]=$val;

 }
 else // it will give element which are at odd index .
 {
 $mydd1[]=$val;
 }

 }
 echo '<pre>'; print_r($mydd1); echo '<pre>'; print_r($mydd);
 ?>

you can see two new arrays $mydd1 and $mydd. $mydd1 will contain odd index based and $mydd will contain even index based element.Here is the output:

Splited array

Here you can see that two arrays first array is of odd index element based and second array  is of  even index element based .

Leave a Reply

Your email address will not be published. Required fields are marked *