Search code examples
phpfunctionrecursionstack-overflow

Stack Overflow and Recursion - How to prevent function from returning to original function when its done?


For Example if i have my code like this (php):

<?php
  somefunc(1);

  function somefunc($a) {
    for($i=1;$i<11;$i++) {
      if ($i==5&&$a) {
        $a--;
        somefunc($a);
      }
      echo "$i <br>";
    }
  }
?>

and the output was

1 2 3 4 1 2 3 4 5 6 7 8 9 10 5 6 7 8 9 10

I want output as

1 2 3 4 1 2 3 4 5 6 7 8 9 10

(the italic part removed)

i dont want it to return to the main function. can something be done about this ?


Solution

  • Just return from the function.

    <?php
    somefunc(1);
    
    function somefunc($a) {
      for($i=1;$i<11;$i++) {
        if ($i==5&&$a) {
          $a--;
          return somefunc($a);
        }
        echo "$i <br>";
      }
    }
    ?>