Assign 2 Numbers to each player from seperate array

I have 2 PHP Arrays, one is filled with players names

$players = array("Player 1", "Player 2", "Player 3", 
                 "Player 4", "Player 5");

Another array is filled with numbers

$numbers= array("1", "2", "3", "4", "5", 
                "6", "7", "8", "9", "10");

I’m trying to figure out how i can assign 2 random numbers to each player

This is where i’m at so far but it’s not doing what i want it to.

foreach($players as $player) {
    shuffle($keys);
    echo $player." 2 Selections:<br />";
    echo $numbers[$keys[0]] . ',' . $numbers[$keys[1]];
    echo "<br /><br />";
    unset($numbers[$keys[0]]);
    unset($numbers[$keys[1]]);
    array_values($numbers);
}

Answer

Something like this:

$players = array("Player 1", "Player 2", "Player 3", "Player 4", "Player 5");

$numbers = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "10");
// shuffle numbers just once
shuffle($numbers);

foreach($players as $player) {
    echo $player." 2 Selections:<br />";
    // `array_pop` takes the last element of array 
    // and reduces array at the same time
    echo array_pop($numbers) . ';' . array_pop($numbers);
    echo "<br /><br />";
}

See the fiddle.

Leave a Reply

Your email address will not be published. Required fields are marked *