1

I want to print 1 to 10 numbers using recursion but its not working.

CODE

  function table($num1) {
      if( $num1 <= 10 ) {
            echo $num1;
            echo "<br>";
            table($num1++);
        }

    }

    $num = 1;
    table($num);

Here's the error

Fatal error: Maximum function nesting level of '256' reached, aborting!

But when I am declaring $num1 as global its working fine. Please anyone tell me the reason behind it.

4 Answers 4

2

table($num1++) means please pass $num1 to table(), and then increase it by one. So this is not what you want.

You have to write table(++$num1) instead. It means increase $num1 first, then pass it to table().

Sign up to request clarification or add additional context in comments.

Comments

0

Because you are passing a variable in copy. So the first variable has still 1 for value, and you are calling infinitely your function "table".

By default, for all variables (with the exception of objects) PHP makes a copy when passing it to a function/method. If you want to pass the same "in-memory" variable, you have to do it by reference.

$myVar=1;
myFunction($myVar);

Before, you declared your function like this:

function myFunction(&myVar) { ...}

Regards

Comments

0
function table($num) {
  if( $num <= 10 ) {
        echo $num;
        echo "<br>";
        table(++ $num);
    }
}
$num = 1;
table($num);

table(++ $num) means increase $num first then pass to table function

1 Comment

Passing by reference is not necessary in this case
0

Try:

function table($value) {
        echo $value;
        echo "<br>";
        $num1=$value+1; 
  if($num1<=10){
        table($num1);
          }
}
$num = 1;
table($num);

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.