constructing a recursive function returning an array

Posted by Admiral Kunkka on Stack Overflow See other posts from Stack Overflow or by Admiral Kunkka
Published on 2012-10-18T22:10:45Z Indexed on 2012/10/18 23:01 UTC
Read the original article Hit count: 256

Filed under:
|
|

I'm developing a function that has a random chance to loop through itself and put it's results in one array for me to use later in my PHP class. Is there a better way to do this more organized, specifically case 5. The array becomes sloppy if it rolls 5, after 5, after 5 looking unpleasant.

private function dice($sides) { return mt_rand(1, $sides); }
private function randomLoot($dice) {
    switch($dice) {
        case 1: $array[] = "A fancy mug."; break;
        case 2: $array[] = "A buckler."; break;
        case 3: $array[] = "A sword."; break;
        case 4: $array[] = "A jewel."; break;
        case 5:
            $array[] = "A treasure chest with contents:";
            $count = $this->dice(3);
            $i = 1;
            while($i <= $count) {
                $array[] = $this->randomLoot($this->dice(5));
                $i++;
            }
        break;
    }
    return $array;
}

© Stack Overflow or respective owner

Related posts about php

Related posts about arrays