⊗ppPmRcEP 218 of 447 menu

Recursion with a Parameter in PHP

Let's use recursion to sequentially output the elements of an array. Let the array initially be passed to the function parameter:

<?php func([1, 2, 3]); ?>

First, let's output all elements of the array one by one using the function array_shift without recursion:

<?php function func($arr) { var_dump(array_shift($arr)); // will output 1 var_dump($arr); // will output [2, 3] - the array has shrunk var_dump(array_shift($arr)); // will output 2 var_dump($arr); // will output [3] - the array has shrunk var_dump(array_shift($arr)); // will output 3 var_dump($arr); // will output [] - the array is empty } func([1, 2, 3]); ?>

As you can see, the function array_shift extracts and returns the first element of the array, while the array itself is reduced by this element.

Now let's use recursion:

<?php function func($arr) { var_dump(array_shift($arr)); var_dump($arr); if (count($arr) !== 0) { func($arr); } } func([1, 2, 3]); ?>

Of course, it is actually easiest to iterate over array elements with a loop. The examples given simply demonstrate the operation of recursion with simple (non-real-world) examples. More useful examples of recursion application are just more complex, we will analyze them a little later.

Given an array:

<?php $arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5]; ?>

Use recursion to output the elements of this array to the screen.

byenru