How can I generate a round robin tournament in PHP and MySQL?

I created a roundrobin function from scratch as i thought it might be easier to get the same results and also allowing me to use arrays filled with strings directly instead of numbers.

Because i pull a list of names from a database and add into an array i can now schedule this directly with below function. No extra step needed to link numbers to names etc.

Please feel free to try it and if it works then leave a comment.
I also have a version which allows for 2 way (home & return) schedule and or shuffle option. If somone is interested in that one then leave a coment as well.

<?php

/**
 * @author D.D.M. van Zelst
 * @copyright 2012
 */

function scheduler($teams){
    if (count($teams)%2 != 0){
        array_push($teams,"bye");
    }
    $away = array_splice($teams,(count($teams)/2));
    $home = $teams;
    for ($i=0; $i < count($home)+count($away)-1; $i++){
        for ($j=0; $j<count($home); $j++){
            $round[$i][$j]["Home"]=$home[$j];
            $round[$i][$j]["Away"]=$away[$j];
        }
        if(count($home)+count($away)-1 > 2){
            array_unshift($away,array_shift(array_splice($home,1,1)));
            array_push($home,array_pop($away));
        }
    }
    return $round;
}
?>

How to use, for example create an array like:

<?php $members = array(1,2,3,4); ?>

or

<?php $members = array("name1","name2","name3","name4"); ?>

then call the function to create your schedule based on above array:

<?php $schedule = scheduler($members); ?>

To display the resulted array schedule simply do like below or anyway you like:
This little code displays the schedule in a nice format but use it anyway you like.

<?php
foreach($schedule AS $round => $games){
    echo "Round: ".($round+1)."<BR>";
    foreach($games AS $play){
        echo $play["Home"]." - ".$play["Away"]."<BR>";
    }
    echo "<BR>";
}
?>

Leave a note if it worked for you or if you are interested in the 2-way version with shuffle.

Leave a Comment