Working with Recursion in PHP
In programming, there is a concept called
recursion - this is when a function calls
itself. Let's look at an example.
Let's output numbers from 1
to 10
using recursion:
<?php
$i = 1;
function func()
{
global $i;
echo $i;
$i++;
if ($i <= 10){
func(); // here the function calls itself
}
}
func();
?>
Let's discuss how this code works.
We have a global variable $i
and a function func
, inside which the content
of the variable $i
is output to the console,
and then ++
is done.
If our variable $i
is less than or
equal to 10
, then the function is called again.
Since the variable $i
is global,
then with each new function call, it will contain
the value of the variable $i
set during the previous call.
It turns out that the function will call itself
until $i
becomes
greater than 10
.
Note that in our case, the function cannot be
started without if
- if you do this,
it will result in an infinite function call.