I have a function like this:
function test($T0){
$T01 = $T0-$T0/2;
$T02 = $T0+$T0/2;
if($T01<$T0){
test($T01);
} else if($T02<$T0){
test($T02);
} else {}
$result = array($T01,$T02);
return $result;
}
$T0 = 50;
$result = test($T0);
echo $result[0];
Why this function is not recursion?
You are missing the return
on your recursive calls:
return test($T01);
and
return test($T02);
In addition, you seem to have strange placement of braces on your else
clause. Most likely it should be:
else {
$result = array($T01,$T02);
return $result;
}
Finally, it's worth noting that this function will (theoretically) cause your code to recurse indefinitely, as you're just dividing a positive number in 2 all the time until it reaches 0. In theory this never happens. In practice, you'll recurse to some very-very small number at which the difference with 0 will be below the floating point precision. In my test this number was 4.9406564584125E-324
(i.e. about 0.0....0494 with ... being 322 zeros).
You are not writing return at the end of your function call, so it is going into an infinite loop
As I debug the code:
In your first condition the
$T01
will become the zero each time. And then it will reach in first condition and call to again to function and you are passing the zero value that time. So the value of $T01 and $T02 becomes zero in second time and it will go in else condition. So This function will not recursion no more again.
Your code is recursive only but the value of t01 is always less than t02, so its going into an infinite loop
To understand recursion you must understand recursion
You forget to return values in your ifs.
Proper code:
<?php
function test($T0){
$T01 = $T0-$T0/2;
$T02 = $T0+$T0/2;
if($T01 < $T0) return test($T01);
else if($T02 < $T0) return test($T02);
else return array($T01,$T02);
}
$T0 = 50;
$result = test($T0);
echo $result[0];
?>