Search code examples
phparraysrandomtournament

How to populate a single tournament elimination randomly in PHP without repeat?


If i have this:

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

How i populate a single tournament elimination like this for example:

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>';
}

?>

Solution

  • This should work for you:

    Just shuffle() your array and then array_chunk() it into groups of 2, e.g.

    <?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>";
    
    ?>