PHP | Separate odd and even elements from array without using loop
You are given an array of n elements in PHP. You have to separate the elements from the array based on the elements are odd or even. That is, print odd array and even array separately without traversing the original array or using any loop.
Input : array(2, 5, 6, 3, 0) Output : Odd array: 5 , 3 Even array: 2, 6, 0 Input : $input = array(0, 1, 2, 3, 4, 5) Output : Odd array: 1, 3, 5 Even array: 0, 2, 4
These type of problems can be easily solved by traversing the array and printing the elements which are odd and even separately, but that will take more lines of code and also a overhead of loop in our code. So, to avoid use of loop we will try to use some inbuilt functions of PHP. Here we are using two PHP array functions array_filter() and array_values() to solve this problem.
- array_filter() : This function will be used to filter the odd/even elements from the input array.
- array_values() : This function will be used to re-index odd and even array as after array_filter odd and even array have same index as their elements have in input array.
Note: The array_filter() function will only filter odd/even indexed element along with their index value. After applying array_filter() function, index of odd-array will be 1, 3, 5 and that of even-array will be like 0, 2, 4.
- Filter elements :
- filter odd elements by array_filter().
- filter even elements by array_filter().
- Re-index Arrays :
- re-index odd-array by use of array_values().
- re-index even-array by use of array_values().
- Print both of the odd/even array.
Below is the PHP implementation of above algorithm:
Odd array : Array (  => 3  => 5  => 7 ) Even array : Array (  => 4  => 6  => 8  => 2 )