How to Separate Odd and Even Elements from an Array Without Using a Loop in PHP

Suppose having an array of n elements, and the task is separating those elements from the array based on they are even or odd. In other words, it is necessary to print an odd array and an even array without using any loop or traversing the initial state of the array.

Below, we will guide you in doing that.

Please consider, first, trying your approach on {IDE} before getting to the solution.

Watch a course Learn object oriented PHP

Using array_filter() and array_values()

If you want to avoid using loops for carrying out the task, mentioned above, then you need to use inbuilt PHP functions such as array_filter() and array_values().

Also, take into account that array_filter() only filters odd/even indexed elements with their index value. After using array_filter(), the index of odd-array is 1, 3, 5 and that of even-array is like 0, 2, 4.

First, let’s see how the algorithm will look like:

  1. Filter elements :
    • filter odd elements by array_filter().
    • filter even elements by array_filter().
  2. Re-index Arrays :
    • re-index odd-array by use of array_values().
    • re-index even-array by use of array_values().
  3. Print both of the odd/even array.

The illustration of the algorithm above will be as follows:


// PHP program to separate odd-even indexed
// elements of an array

// input array
$input = [4, 3, 6, 5, 8, 7, 2];

// comparator function to filter odd elements
function oddCmp($input)
    return $input & 1;

// comparator function to filter odd elements
function evenCmp($input)
    return !($input & 1);

// filter odd-index elements
$odd = array_filter($input, "oddCmp");

// filter even-index elements
$even = array_filter($input, "evenCmp");

// re-index odd array by use of array_values()
$odd = array_values(array_filter($odd));

// re-index even array by use of array_values()
$even = array_values(array_filter($even));

// print odd-indexed array
print "Odd array :\n";

// print even-indexed array
print "\nEven array :\n";
Odd array :
    [0] => 3
    [1] => 5
    [2] => 7

Even array :
    [0] => 4
    [1] => 6
    [2] => 8
    [3] => 2

Describing the Array_filter Function

This function is capable of iterating over every value in the array and pass them to the callback function.

Once the callback function returns True, the current value from the array gets back into the result array.

The array_filter function has the following parameters: array, callback, and flag.

The first one is the array to iterate over. Callback is the callback function to apply. And, the flag specifies what arguments are forwarded to the callback.

Describing the array_values() Function

This function is used for returning all the values from the array and indexing the array numerically. It is mainly used when the exact key or index of the array is now known.