Search code examples
phparraysrandomphp-5.3

Move 7 random elements from one array to another


In a word game with 2 players I would like to give 7 random letters to each player in the PHP 5.3 function creating a new game:

$LETTERS = array( '*', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' );
$NUMBERS = array(  2,  10,   3,   5,   3,   5,   9,   2,   2,   8,   4,   6,   4,   5,   8,  10,   6,   6,   6,   5,   3,    1,   2,   1,   2,   1,   1 );

function createGame($dbh, $uid) {
        global $LETTERS, $NUMBERS;
        $letters  = array();
        $letters1 = array();
        $letters2 = array();

        for ($i = 0; $i < count($LETTERS); $i++) {
                $letter = $LETTERS[$i];
                $number = $NUMBERS[$i];

                for ($n = 0; $n < $number; $n++) {
                        array_push($letters, $letter);
                }
        }

        for ($i = 0; $i < 7; $i++) {
                /* TODO move random letter from $letters to $letter1 */
                /* TODO move random letter from $letters to $letter2 */
        }

        $sth = $dbh->prepare('insert into games (player1, stamp1, stamp2, letters1, letters2, letters, board) values (?, unix_timestamp(now()), 0, ?, ?, ?, space(225))');
        $sth->execute(array($uid, join('', $letters1), join('', $letters2), join('', $letters)));
        return $dbh->lastInsertId();
}

I know that array_rand() can be used to select a random element from an array.

But how to use it here in a most effective way to move a letter from the $letters array?

UPDATE:

I've tried the following, but the first 7 letters are not removed from the beginning of the source array, why?

    shuffle($letters);
    $letters1 = array_slice($letters, 0, 7);
    $letters2 = array_slice($letters, 0, 7);

Solution

  • I would shuffle the array of letters and remove the first element of the shuffeld array to get one random letter.

    shuffle($letters); // Mix alle array elements
    for ($i = 0; $i < 7; $i++) {
      $letters1[] = array_shift($letters); // get first array element, removing it from $letters
      $letters2[] = array_shift($letters); // get first array element, removing it from $letters
    }