Creating variable variables and or storing variables in an array

Hello everyone. I am doing my first PHP mini project, which is a D&D style dice rolling offspring generator for a game I play online. I am creating a 6-sided dice roll using mt_rand(1, 6). Depending on the outcome of each roll, a different number of rolls is required next time.

[php]
$total=mt_rand(1, 6); //Total number of offspring
$puppies=$total; //This variable gets eaten by the loop below (if you have any ideas please say so!)
[/php]

So now we have a random number 1-6 and I want to roll dice equal to that number, and record the values. I have attempted several and none seem to work.

[php]
for ($puppies; $puppies>=1; $puppies–)
{
${death.$i} = mt_rand(1, 6);
}
// OR
$death = mt_rand(1, 6);
$fatality[] = $death[0];
// OR
$fatality = array (“death1”=>mt_rand(1, 6), “death2”=>mt_rand(1, 6));
[/php]

So ideally I want it to say, you have x total, roll x times and record those numbers either as variables or as an array. There’d only ever be six maximum so I guess it doesn’t matter which way. I’ve tried making six ${$fatality[0]} = mt_rand(1, 6); but I obviously don’t want to display 6 dice rolls if I only had 3 to start with (and thus need 3 dice rolls). Equally, I guess this method would work if I knew how to echo only the number of $fatality as $total?

Any help is greatly appreciated! Many thanks!

Hi!

Do you mean:
[php]
$top = mt_rand( 1, 6 ); // Generates $top with value 1,2,3,4,5 or 6
$sub = array();

for ( $i=1; $i<=$top; $i++ ) // Counts from 1 to $top
{ $array[] = mt_rand( 1, 6 ); // Pushes value 1,2,3,4,5 or 6 onto the array for every count
}

echo “Top…: $top
\n”;
echo "Children…: ". implode( ', ', $array ). “\n”;
[/php]
( Please ask if you need a more elaborate description )

Good luck! ;D
O.

Sorry for the late reply, I am on a business trip and haven’t been able to play around with my project. I will try this as soon as I find a moment. Thank you so much for taking the time to help me!

[php]for ($puppies; $puppies>=1; $puppies–)
{
${death.$i} = mt_rand(1, 6);
}[/php]

is not a proper for loop… It should be…

[php]for ($i=$puppies; $i>=1; $i–)
{
${death.$i} = mt_rand(1, 6);
}

or

for ($puppies; $puppies>=1; $puppies-)
{
${death.$puppies} = mt_rand(1, 6);
}[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service