3v4l.org

run code in 300+ PHP versions simultaneously
<?php $players = array ( 0 => array ( 'ID' => '3', 'name' => 'olaf', 'team' => NULL, ), 1 => array ( 'ID' => '4', 'name' => 'Peter', 'team' => NULL, ), 2 => array ( 'ID' => '5', 'name' => 'chris', 'team' => NULL, ), 3 => array ( 'ID' => '6', 'name' => 'günther', 'team' => NULL, ), 4 => array ( 'ID' => '7', 'name' => 'John', 'team' => NULL, ), 5 => array ( 'ID' => '8', 'name' => 'Jack', 'team' => NULL, ), 6 => array ( 'ID' => '9', 'name' => 'Bob', 'team' => NULL, ), 7 => array ( 'ID' => '10', 'name' => 'Jake', 'team' => NULL, ), 8 => array ( 'ID' => '11', 'name' => 'Bill', 'team' => NULL, ) ) ; function constTeams($players){ $numOfPlayers = count($players); $check = array(); $i = 0; while($i < count($players)){ foreach($players as $key => $value){ $random = rand(1,$numOfPlayers); if(!in_array($random, $check) && !array_key_exists($value['name'], $check)){ $check[$value['name']] = $random; $i++; } } } if(count($check) === count($players)){ // no assign team $teamOne = '<br>Team one: '; $teamTwo = '<br>Team two: '; foreach($players as $key => $value){ $gamers[$key] = $value; if($check[$value['name']] % 2 == 0){ $gamers[$key]['team'] = 'Blue'; }else{ $gamers[$key]['team'] = 'Red'; } } } return $gamers; } $output = ' <table> '; foreach(constTeams($players) as $key => $value){ $output .= ' <tr border="1"> <td>'.$value['name'].'</td> <td>Team: '.$value['team'].'</td> </tr>'; } $output .= ' </table>'; echo $output;

preferences:
37.6 ms | 405 KiB | 5 Q