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:

 $dd=array(); // declared first array

 $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.

 else // it will give element which are at odd index .

 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 *