0

If we are using recursive function call how the memory allocated for the variables. While running below code its echo 2 as result.Can anyone please guide me why the value of $a not taking in any of this loop iteration. if i set

$a= recursionfunction($a); 

with in the function its will works fine.

function recursionfunction($a)
{
    if($a<10)
    {
        $a=$a+1;
        recursionfunction($a);

    }
   return $a;

}
$result = recursionfunction(1);
echo $result
AGK
  • 86
  • 1
  • 13

1 Answers1

1

Assuming you mean recursionfunction( 1 ) instead of abc( 1 ), you are missing a return in your function:

function recursionfunction($a)
{
    if($a<10)
    {
        $a=$a+1;
        return recursionfunction($a);
// missing -^
    }else{
        return $a;
    }

}
$result = recursionfunction(1);
echo $result

EDIT

After your (substantial) edit, the whole case is different. Let's go through the function line by line, to see, what happens:

// at the start $a == 1, as you pass the parameter that way.

// $a<10, so we take this if block
    if($a<10)
    {
        $a=$a+1;
// $a now holds the value 2

// call the recursion, but do not use the return value
// as here copy by value is used, nothing inside the recursion will affect
// anything in this function iteration
        recursionfunction($a);
    }

// $a is still equal to 2, so we return that
   return $a;

More details can be found at this question: Are PHP Variables passed by value or by reference?

Probably you again, want to add an additional return statement, to actually use the value of the recursion:

function recursionfunction($a)
{
    if($a<10)
    {
        $a=$a+1;
        return recursionfunction($a);
// add ---^
    }
   return $a;
}
Community
  • 1
  • 1
Sirko
  • 72,589
  • 19
  • 149
  • 183