-1

I'd like to return some value using a recursive function. Unfortunately the function doesn't return anything until I change return to echo. Here is a similar function I created for better understanding.

function debug($a, $i) {
    $a .= $i;

    if ($i !== 5) {
      $i++;
      debug('echo', $i);
    } else {
      return $a; // expecting echo5 (echo works perfectly)
    }
}

echo debug('echo', 0); // doesn't return anything
cca
  • 69
  • 7

2 Answers2

2

Just return the value from the recursive call in order to catch the result.

EDIT:

Here is a new way of handling your code.

  • If the number you are passing is greater than five then subtract 1 every recursive call.
  • If the number is lower than five than add 1 every recursive call.
  • Otherwise it returns 5.

So when it reaches five, the output will be for example echo012345 or echo98765.


If you want to limit the output to echo5, then you should wrap $a .= $i with an if statement to check if ($i == 5).

<?php
function debug($a, $i) {
   $a .= $i;

   if ($i > 5) {
       $i--;
       return debug($a, $i);
   } elseif ($i < 5) {
       $i++;
       return debug($a, $i);
   }
   return $a;
}

echo debug('echo', 10);

?>
Abdulrahman Hashem
  • 1,481
  • 1
  • 15
  • 20
  • Thanks for your effert. But in this case the function loops endless, doesn't it? – cca May 17 '20 at 11:35
0

The function is working 100% as intended. You do not print the value simply because the function is "returning" it. If you want the value printed, then you must echo it as you've observed yourself.

Think of it this way:

Return - returns the value in raw data.

echo - prints stuff.

Also the way your recursive function works now, it only contains the return value within its scope, so the value is "dropped" when the execution is completed. That's why you won't be able to echo anything. When you echo inside the function, it's echoing the value before stopping the execution.

One way to circumvent this, is by adding a print parameter to the function if you wish for your value to be printed,

Example:

function debug($a, $i, $print=false) {
    $a .= $i;
    if($i < 5) {
        $i++;
        debug('echo', $i, $print);
    } else{
        if($print){
            echo $a;
        }
        return $a;
    }
}
debug('echo', 0, true);
Martin
  • 2,326
  • 1
  • 12
  • 22
  • Thanks for your answer. But shouldn't `echo debug('echo', 0)` return `echo5` which is saved in `$a`? I need the return value. – cca May 17 '20 at 11:07
  • I get the following error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 16384 bytes). In this case the function loops endless. – cca May 17 '20 at 11:33
  • You're right. What you could do is add a print parameter to be parsed with the function if you wish to have your value printed. That's one way to get around the problem at least... Check updated answer. – Martin May 17 '20 at 12:32