0

Am I missing something? In trying to implement an algorithm I can't obtain a return value for a function. Originally trying to return an array I've encountered simple types won't work as well.

NOTE: This is a simplified version to illustrate the point. I'm aware that for the illustrated code one could use something like print_r(array_map(function($x){return $x+2;}, array(2, 4, 6, 8))); but this won't do in the full problem.

And for the question. I have the following code:

function recursive1($myArray, $accumulator){
  if(empty($myArray)){
    return $accumulator;
  } else {
    recursive1(array_slice($myArray, 1), $accumulator+1);
  }
}
$testArray = array(3, 5, 7, 9);
print("->".recursive1($testArray,10)."<-\n");

Getting nil as a result

(output)
-><-

Adding a little to see the internals I have

function recursive1($myArray, $accumulator){
  if(empty($myArray)){
    print("[".$accumulator."]\n");   // End result
    return $accumulator;
  } else {
    print("<".$accumulator.">");   // partial results
    recursive1(array_slice($myArray, 1), $accumulator+1);
  }
}
$testArray = array(3, 5, 7, 9);
print("->".recursive1($testArray,10)."<-\n");

I get that the function it's doing what it suppose to do but the return value is lost.

(output)
<10><11><12><13>[14]
-><-

So I should have

(output)
->14<-

By the way I'm using

>php -version
PHP 5.5.30 (cli) (built: Oct 23 2015 17:21:45)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.5.0 Copyright (c) 1998-2015 Zend Technologies

I've also tried to assign the value to a variable (outside the function) to no avail.

Any ideas? :-)

3 Answers3

3

You're missing a return statement and so your function returns nothing in the recursive branch. Change this line:

recursive1(array_slice($myArray, 1), $accumulator+1);

to

return recursive1(array_slice($myArray, 1), $accumulator+1);    
Asaph
  • 159,146
  • 25
  • 197
  • 199
2

You should have this:

else {
   print("<".$accumulator.">");   // partial results
   return recursive1(array_slice($myArray, 1), $accumulator+1);
}

Without the return statement, your final result is never returned.

olibiaz
  • 2,551
  • 4
  • 29
  • 31
1

You need to add return to your recursive call:

return recursive1(array_slice($myArray, 1), $accumulator + 1);
Davis
  • 856
  • 4
  • 11