I try to get the value 10
but it comes NULL
. What goes here wrong? Tested on PHP 5.3
<?php
function foo($i=0){
if($i<10) foo($i+1);
else return $i;
}
$value = foo();
var_dump($value);
?>
If i
is 10 in foo
, the value 10 is returned to the calling instance of foo
(where i
was 9) and then the function ends without an return statement.
You probably want
function foo($i=0) {
if($i<10)
return foo($i+1);
return $i;
}
You code works like this:
function foo($i=0){
if($i<10)
foo($i+1);
else
return $i;
return; // implicit return
}
Since $i
< 10 you recur until it's 0 but the return value isn't returned or used. Outside of the if
there is an implicit return that returns no value.
In order to return the value from the recursion you need a return statement:
function foo($i=0){
if($i<10)
return foo($i+1);
else
return $i;
}
try
if($i<10)
return foo($i+1);
else
return $i;
because otherwise it never returns.
You should return the value:
function foo($i=0){
if($i<10) {
return foo($i+1);
} else {
return $i;
}
}
try:
function foo($i) {
if ($i < 10) {
echo "a",$i;
$i=foo(($i + 1));
}
return $i;
}
For Your understanding echo $i
and then test at the last function never calls the else statement try without else
statement.
function foo($i=0){
if($i<10){
foo($i+1);
echo $i;
}
return $i;
}
$value = foo();
var_dump($value);