-2

I have a methos

private function test($testArray = array(),$i=0){
        $i++;
        $testArray = array_merge($testArray, array($i));
        if($i < 10){
            $this->test($testArray, $i); //recursion
        }else{
            return $testArray;
        }
    }

when I call it like $x = $this->test(array(), 0); from another method, it is suppose to make an array of $i and then return that array when $i reaches 10. Issue is that it returns null what makes it interesting is that when I do var_dump I get the array right before the return. here is what I have in debug code

private function test($testArray = array(),$i=0){
    $i++;
    $testArray = array_merge($testArray, array($i));
    var_dump($i);
    if($i < 10){
        var_dump("Continued to $i");
        $this->test($testArray, $i);
    }else{
        var_dump("Closing on $i");
        var_dump($testArray);
        return $testArray;
    }
}

and here is the output

int 1
string 'Continued to 1' (length=14)
int 2
string 'Continued to 2' (length=14)
int 3
string 'Continued to 3' (length=14)
int 4
string 'Continued to 4' (length=14)
int 5
string 'Continued to 5' (length=14)
int 6
string 'Continued to 6' (length=14)
int 7
string 'Continued to 7' (length=14)
int 8
string 'Continued to 8' (length=14)
int 9
string 'Continued to 9' (length=14)
int 10
string 'Closing on 10' (length=13)
array (size=10)
  0 => int 1
  1 => int 2
  2 => int 3
  3 => int 4
  4 => int 5
  5 => int 6
  6 => int 7
  7 => int 8
  8 => int 9
  9 => int 10
null

this is killing me any help will be appreciative

hakre
  • 193,403
  • 52
  • 435
  • 836
Asim Zaidi
  • 27,016
  • 49
  • 132
  • 221
  • 2
    If the `if` statement is true, your code isn't actually returning anything - it only returns a variable when it's false. – andrewsi Oct 29 '13 at 17:00
  • what do you mean? It should return array – Asim Zaidi Oct 29 '13 at 17:04
  • No. If `if($i < 10){` is true, you call the function recursively, but you don't ever return the value from that function call. The only time you'll return anything is when the `else` statement is resolved. In that case, control will return to the previous function call, but since there's no `return`, it will end up returning null. – andrewsi Oct 29 '13 at 17:07
  • Duplicate of: https://stackoverflow.com/q/31624313/9473764 – mickmackusa May 28 '22 at 02:58

2 Answers2

1

I think the one simple change to make is:

private function test($testArray = array(),$i=0){
    $i++;
    $testArray = array_merge($testArray, array($i));
    if($i < 10){
        return $this->test($testArray, $i); //recursion
    }else{
        return $testArray;
    }
}
SamA
  • 587
  • 3
  • 6
1

You aren't actually returning anything at the end. The if statement will evaluate to true every time and make the function call itself. When they all finally finish, a return statement is never actually called.

Jonathon
  • 15,873
  • 11
  • 73
  • 92