DEV Community

Cover image for Reverse an array in PHP by using recursion
Yongyao Yan
Yongyao Yan

Posted on • Updated on • Originally published at codebilby.com

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

and

if ($n == 1) return 1;
Enter fullscreen mode Exit fullscreen mode

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;

} 
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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

$result =  insertToFront($key, reverseArray($value), $result);
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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)); 
Enter fullscreen mode Exit fullscreen mode

...

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

Discussion (2)

Collapse
tw2113 profile image
Michael Beckwith

My biggest question is...why? The native functions are available in all major versions still in production. Why recreate the wheel with this topic, other than perhaps to say you could?

Collapse
yanyy profile image
Yongyao Yan Author

The point is to use a very common example to show a recursive algorithm.