PHPRO.ORG

For those who have ever wanted to run a football league, or any sort of league requiring a round robin style of game draws, this simple function takes an array of team names (or numbers) and returns an array of the teams' games. This function also takes into account byes when an odd number of teams is given.


<?php

/**
 *
 * Create a round robin of teams or numbers
 *
 * @param    array    $teams
 * @return    $array
 *
 */
 
function roundRobin( array $teams ){

    if (
count($teams)%!= 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)-2)
        {
            
$s array_splice$home1);
            
$slice array_shift$s  );
            
array_unshift($away,$slice );
            
array_push$homearray_pop($away ) );
        }
    }
    return 
$round;
}
?>

Usage


<?php

// create an array of teams
$members = array('team1','team2','team3','team4''team5''team6''team7''team8''team9');

// do the rounds
$rounds roundRobin($members);

$table "<table>\n";
foreach(
$rounds as $round => $games){
    
$table .= "<tr><th>Round: ".($round+1)."</th><th></th><th>Away</th></tr>\n";
    foreach(
$games as $play){
       
$table .= "<tr><td>".$play["Home"]."</td><td>-v-</td><td>".$play["Away"]."</td></tr>\n";
    }
}
$table .= "</table>\n";

echo 
$table;
?>

Demonstratrion

Round: 1Away
team1-v-team6
team2-v-team7
team3-v-team8
team4-v-team9
team5-v-bye
Round: 2Away
team1-v-team2
team3-v-team6
team4-v-team7
team5-v-team8
bye-v-team9
Round: 3Away
team1-v-team3
team4-v-team2
team5-v-team6
bye-v-team7
team9-v-team8
Round: 4Away
team1-v-team4
team5-v-team3
bye-v-team2
team9-v-team6
team8-v-team7
Round: 5Away
team1-v-team5
bye-v-team4
team9-v-team3
team8-v-team2
team7-v-team6
Round: 6Away
team1-v-bye
team9-v-team5
team8-v-team4
team7-v-team3
team6-v-team2
Round: 7Away
team1-v-team9
team8-v-bye
team7-v-team5
team6-v-team4
team2-v-team3
Round: 8Away
team1-v-team8
team7-v-team9
team6-v-bye
team2-v-team5
team3-v-team4
Round: 9Away
team1-v-team7
team6-v-team8
team2-v-team9
team3-v-bye
team4-v-team5