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
2
  • $result = abc(1); - clearly you've got some copy and paste weirdness going on. Commented Oct 28, 2013 at 9:15
  • Your if part doesn't return anything. Also, may we safely assume that abc() is the same as recursionfunction()? Commented Oct 28, 2013 at 9:16

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.