constructing a recursive function returning an array
- by Admiral Kunkka
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;
}