-4

Here is a function in PHP that generates a random number between 1 and 15 and store that number in a array and keep calling itself to repeat until the array contains five elements, at which point, you can make it either print/echo out the elements of the array or return the array. My problem is that when I try to get it to return the array and assign it to the variable $result, I get nothing. Any ideas as to what's going on?

$storenumbers = array();

function storemynumbers($storenumbers){
    $number = rand(1,15);

    if(count($storenumbers) == 5){
        echo "Done<br/>";
        print_r($storenumbers);
        //return $storenumbers;
    }else{
        echo $number."<br/>";
        $storenumbers[] = $number;
        storemynumbers($storenumbers);
    }
}

//$result = storemynumbers($storenumbers);
//print_r($result);

storemynumbers($storenumbers);
Jakub
  • 20,418
  • 8
  • 65
  • 92

4 Answers4

1

Because you are only returning anything on the last run, which gets passed back to the next-to-last run, which is then dropped.

In your else block, try adding return in front of storemynumbers($storenumbers). This should pass the return value all the way back down the chain.

That said, why can't you just do:

$storenumbers = Array();
for( $i=0; $i<5; $i++) $storenumbers[] = rand(1,15);
print_r($storenumbers);
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Because I need it to be a recursive function. This is just a simplified version of a much more complicated script I'm working on which uses a recursive function. – freemarlie Nov 13 '11 at 10:32
0

becouse you need to pass parameter by reference(& before parameter): like this:

function storemynumbers(&$storenumbers){
}

By default variables are local copy, so they not visible outside function.

Kamil Lach
  • 4,519
  • 2
  • 19
  • 20
0

missing return on the recursion. would be my guess.

$storenumbers = array();

function storemynumbers($storenumbers){
    $number = rand(1,15);

    if(count($storenumbers) == 5){
        echo "Done<br/>";
        print_r($storenumbers);
        return $storenumbers;
    }else{
        echo $number."<br/>";
        $storenumbers[] = $number;
        return storemynumbers($storenumbers);
    }
}

$result = storemynumbers($storenumbers);
print_r($result);
caguilar187
  • 753
  • 3
  • 10
0

This is a easy way to create a array of $max random number between 1 and 15.

function storemynumbers($max, $start, $end) {
    $store = array();

    for( $i=0; $i<$max; $i++) {
        $store[] = rand($start, $end);
    }

    return $store;
 }

$result = storemynumbers(5, 1, 15);
print_r($result);

You could also use a reference to a variable

malletjo
  • 1,766
  • 16
  • 18