0

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);

?>
markus
  • 561
  • 4
  • 15

6 Answers6

4

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;
}
Jasper
  • 3,939
  • 1
  • 18
  • 35
2

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;
}
Sylwester
  • 47,942
  • 4
  • 47
  • 79
2

try

if($i<10) 
  return foo($i+1);
else 
  return $i;

because otherwise it never returns.

ponciste
  • 2,231
  • 14
  • 16
1

You should return the value:

function foo($i=0){
  if($i<10) {
    return foo($i+1);
  } else {
    return $i;
  }
}
nxu
  • 2,202
  • 1
  • 22
  • 34
1

try:

function foo($i) {

if ($i < 10) {
    echo "a",$i;
    $i=foo(($i + 1));
}

return $i;

}

Rotari Radu
  • 645
  • 6
  • 13
0

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);
Nambi
  • 11,944
  • 3
  • 37
  • 49
  • 1
    It will in the 10th recursion or if you call it with 10. $i=0 make 0 the default value only and every recursion supplies an argument. – Sylwester Apr 08 '14 at 09:15