Can anyone explain to me what is actually going on in the function?
function f($b=0)
{
echo $b.',';
/*otuput is 0,1,2,3,4,5,3,4,2,3,4,5,3,*/
if ($b<3)
{
/*echo $b.',';
when echo is here, otuput is 0,1,2,2,*/
for ($a=0;$a<3;$a++)
{
/*echo $b.',';
when echo is here, otuput is 0,1,2,3,4,2,3,1,2,3,4,2,*/
f(++$b);
}
}
}
f();
Why is output not 0,1,2,0,1,2,0,1,2,
? And how to do with the calling same function from function?
First of all it calls f(0)
so it displays 0
.
Then it calls f(1)
, f(2)
& f(3)
respectively.
f(1)
: It displays 1
and runs f(2)
, f(3)
& f(4)
.
f(2)
: It displays 2
and runs f(3)
, f(4)
& f(5)
.
f(3)
: It displays 3
only
f(4)
: It displays 4
only
f(5)
: It displays 5
only
...
So:
f(0):
{
0,
f(1):
{
1,
f(2):
{
2,
f(3):
{
3
},
f(4):
{
4
},
f(5):
{
5
}
},
f(3):
{
3
},
f(4):
{
4
}
},
f(2):
{
2,
f(3):
{
3
},
f(4):
{
4
},
f(5):
{
5
}
},
f(3):
{
3
}
}
So the output is: 0,1,2,3,4,5,3,4,2,3,4,5,3,
This is an effect of recursion. The variable b
is always within local scope of the function. When you first start the function, b
value is 0, therefore reaches the for. The ++b
syntax means that b is increased before being evaluated, so when reaching f(++b)
with b == 0
, it becomes a f(1)
. The function then starts the cycle with b == 1
, and reaches the for. At this point, contrary to what you were expecting, you have the first for still waiting for recursion to finish, when you start the new recursion cycle. This also happens for the next recursion, with b==2
. So, using some indentation to clarify the cycles:
// Prints 0
for ($a = 0; $a < 3; $a++)
f(++$b) // $b == 0, $a == 0
// Prints 1
for ($a = 0; $a < 3; $a++)
f(++$b) // $b == 1, $a == 0
// Prints 2
for ($a = 0; $a < 3; $a++)
f(++$b) // $b == 2, $a == 0
// Prints 3, no further cycles
f(++$b) // $b == 3, $a == 1
// Prints 4, no further cycles
f(++$b) // $b == 4, $a == 2
// Prints 5, no further cycles
// The function returns having completed the cycle
f(++$b) // $b == 2, $a == 1
// Prints 3, no further cycles
f(++$b) // $b == 3, $a == 2
// Prints 4, no further cycles
// The function returns having completed the cycle
f(++$b) // $b == 1, $a == 1
// Etc. etc.