Search code examples
phpfunctionscopeglobal-variables

Can variables declared inside of a function's scope be accessed in the global scope?


I am currently trying to create a team generator for a game that organizes teams based on player ratings. I am having a little issue when it comes to adding players in a nested array. I will eventually be adding database calls to the arrays. I can't figure out why I can't echo the players after I try and add them to the teams array. The randoms are for testing purposes.

$players = array();
$captains = array();
for ($i = 1; $i <= 40; $i++){
  $players[] = array('name' => 'Player ' . $i, 'MMR' => rand(2800,4200));
}
for ($i = 1; $i <= 10; $i++){
  $captains[] = array('name' => 'Captain ' . $i, 'MMR' => rand(3200,4200));
}

//sort the players by MMR
usort($players, function($a, $b) {
  return $a['MMR'] - $b['MMR'];
});

 //sort the captains by MMR
usort($captains, function($a, $b) {
   return $a['MMR'] - $b['MMR'];
});

//put captains on teams
$teams = array();
for($i = 0;$i < count($captains); $i++){
  $teams[] = array('name' => 'Team ' . ($i + 1), 'captain' => $captains[$i], 'players' => array(), 'totalMMR' => $captains[$i]['MMR']);
}

Here is where I think the problem may be:

function addPlayer($team,$newPlayer){
  $teams[$team]['players'][] = $players[$newPlayer];
  $teams[$team]['totalMMR'] += $players[$newPlayer]['MMR'];
 }

addPlayer(0,0);

$output = '';
foreach($teams as $team){
  $output .= '<div class="teams">' . $team['name'] . '<br />' . $team['captain']['name'] . ': ' . $team['captain']['MMR'] . '<br />';
for ($i = 0; $i < count($team['players']); $i++){
$output .= $team['players'][$i]['name'] . ': ' . $team['players'][$i]['MMR'] . '<br />';
}
$output .= '</div>';
}
echo $output;

Now the captains are echoing out, but the player that I added is not. Any help would be appreciated.


Solution

  • function addPlayer($team,$newPlayer){
        $teams[$team]['players'][] = $players[$newPlayer];
        $teams[$team]['totalMMR'] += $players[$newPlayer]['MMR'];
    }
    

    There's no variable named $teams in this function. If you mean to modify a global variable named $teams, then you can say global $teams; as the first line in your function.

    Likewise for $players (although you should have gotten a notice about undefined indexes).