I recently started a little project in PHP, I’m sort of new to this and this may be a beginner question but I can’t find any help so I’m asking here.
I am working on a card game and I want to give up to six players random cards. I store how many cards everyone gets in $cardstoget and how many players there are in $player. I have an array $usedcards with values like [0] => 0, [1] => 0 and so on. I determine if the card is already used by putting it to 1 instead of 0 like this: [1] => 1. There are 80 cards and I plan on having [0] filled with the number of unused cards left.
I use this code:
for ($i = 1;$i <= $player;$i++) {
for ($i2 = $cardstoget;$i2 > 0;$i2--) {
do {
$temp = mt_rand(1,80);
} while ($usedcards[$temp] = 1);
${"cards".$i} = ${"cards".$i} . $temp;
$usedcards[$temp] = 1;
}
}
When I execute the code I get this error message:
Fatal error: Maximum execution time of 30 seconds exceeded in /var/www/create.php on line 47
So now to my question: How can I change the do-while loop to make it to something similar but faster? I know this loop is the problem, I tried it without and it worked fine,but I can’t know it this card is already on someone’s hand.
I hope somebody out there can help me and any help is highly appreciated.
Your immediate problem is the
$usedcards[$temp] = 1condition. You’re assigning1here, which results in the condition always beingtrue, and the loop looping endlessly.More generally, you’ll want a deterministic algorithm, not one whose completion depends on randomness. Something like:
This mimics a real shuffling-and-distribution of cards as you’d do in a real game.