Reverse an array in PHP by using recursion

Reverse an array in PHP by using recursion

Let's go back to a computer science textbook topic. Show you how to reverse an array in PHP without using any native array functions such as array_xxx().

Recursion

Recursion is a process in computer science to make a function call itself. The corresponding function is called recursive function. Certain complicated problems can be solved easily by using the recursive method.

The best way to understand the recursive function is to show you the example of Fibonacci nunmbers. The Fibonacci numbers can be defined as:

F(0) = 0, F(1) = 1
F(N) = F(N-1) + F(N-2) (N > 1)

The recursive function for the Fibonacci nunmbers is:

function F(int $n): int {
    if ($n == 0) return 0; // Stop condition
    if ($n == 1) return 1; // Stop condition

    return F($n - 1) + F($n - 2);

}

 echo 'F(18) = ' . F(18); // F(18) = 2584

The most important thing in a recursive function is the stop condition, where the function stops calling itself. In the code snippet above, there are two stop conditions:

if ($n == 0) return 0;

and

if ($n == 1) return 1;

These stop conditions are the cases for F(0) = 0 and F(1) = 1. When N > 1, the recursive function calls itself and returns the value of F($n - 1) + F($n - 2). If no stop condition is defined, a recursive function can run into the problem of infinite resursion. This is like the case of infinite looping.

Reversing an array

This is an example of using recursion to reverse an array without using the native array functions, i.e. array_xxx(), in PHP.

We define a recursive function called reverseArray(array $array) to reverse an array. It iterates over an input array and reverses each element's position by calling the function insertToFront() where each element read from the input array is put in the front of the return array $result.

function reverseArray(array $array) {
    $result = [];
    foreach ($array as $key => $value) {
        // check if it is an array
        if (is_array($value)) {
            // insert into the front of the result array
            $result =  insertToFront($key, reverseArray($value), $result);
            continue;
        }      
        $result = insertToFront($key, $value, $result);  
    }
    return $result;

}

In the recursive function reverseArray(array $array), the stop condition is when the element's value type is not an array. Each iterated array element is put to the front of the return array $result in turn:

$result = insertToFront($key, $value, $result);

If the element's value type is an array, the recursive function is called to reverse this array:

$result =  insertToFront($key, reverseArray($value), $result);

The processure of putting an array element to the front of the return array is as below:

function insertToFront($key, $value, $array) {

    $result = [];
    // insert into the front of the result array 
    $result[$key] = $value;

    // append all the rest data
    foreach ($array as $oldKey => $oldValue) {
        $result[$oldKey] = $oldValue;
    }       

   return $result;
}

To test the recursive function reverseArray(array $array), first, let's test with the indexed array:

// Indexed array
$inputArray = [1, 2, 3, 4, 5]; 

echo 'Before Reverse:' . PHP_EOL;
var_dump($inputArray);
echo 'After Reverse:' . PHP_EOL;
var_dump(reverseArray($inputArray));

...

For the rest of the content, please go to the link below: https://www.codebilby.com/blog/a41-reverse-an-array-in-php-by-using-recursion

Did you find this article valuable?

Support Yongyao Yan by becoming a sponsor. Any amount is appreciated!