How to fill in a single tournament selection randomly in PHP without repeating?

If I have this:

$players = array("A","B","C","D","E","F","G","H","I","J","L","M","N","O","P","Q");

      

How can I fill one tournament exception like:

Matche 1: AxL
Matche 2: CxJ
Matche 3: HxQ
.
.
.
Matche 8: ExP

      

16 Players = 8 Matches

I try this and other codes too:

<?php

$players = array("A","B","C","D","E","F","G","H","I","J","L","M","N","O","P","Q");
shuffle ($players);

foreach($players as $key=>$value)
{
    echo $value.','.$value.'<br>';
}

?>

      

+3


source to share


2 answers


This should work for you:

Just shuffle()

your array and then array_chunk()

into groups of 2, like



<?php

    $players = ["A","B","C","D","E","F","G","H","I","J","L","M","N","O","P","Q"];
    shuffle($players);
    $players = array_chunk($players, 2);

    foreach($players as $match => $player)
        echo "Match " . ($match+1) . ": " . $player[0] . "x" . $player[1] . "<br>";

?>

      

+6


source


Use the suffle function to randomize the order of the players and read the array in steps of 2



shuffle($players);

for ($x = 0; $x < count($players); $x += 2) {
  echo "Match " . (($x/2)+1) . ": " . $players[$x] . "x" . $players[$x+1] . "\n";
}

      

+2


source







All Articles