Take this problem using an example of teams and individual players (who can belong to multiple teams):-

Each player stores a boolean value of male (0/1) and female (0/1) to delineate its sex. When a team is edited, it counts the number of male and female members on its team and creates a respective total for both. Should an individual player be edited and have their sex changed (perhaps data was initially entered incorrectly), when updating I need to update the counts of all the player's associated teams as well.

I've got this to work should the person only have one associated team, but for multiple teams the counts accumulate with each iteration of the foreach loop (i.e. the second team would have the sum of teams 1 and 2, the third team the sum of teams 1, 2 and 3, etc,).

Basically, I need to reset the 'player_male_arr' and 'player_female_ arr' arrays for each team (and the unset function doesn't seem to be doing that or I am not using it in the right place).

Below is the player index code.

Thanks for any help.

PHP Code:
$sql "SELECT
        teamid
        FROM
        teamplayer
        WHERE playerid = '
$player_id'"//selects associated team ids of player
while ($row mysqli_fetch_array($result))
{
    
$assoc_team_ids[] = $row['teamid'];
}
foreach(
$assoc_team_ids as $assoc_team_id)
{
    
$assoc_team_id $assoc_team_id['teamid'];

    
$sql "SELECT
            player_sex_male,
            player_sex_female,
            FROM teamplayer
            INNER JOIN player
            ON playerid = player_id
            WHERE teamid = '
$assoc_team_id'"//selects male/female data for associated teams
    
$result mysqli_query($link$sql);

    while (
$row mysqli_fetch_array($result))
    {
        
$player_counts[] = array('player_sex_male' => $row['player_sex_male'], 'player_sex_female' => $row['player_sex_female']);

        
$player_male_arr = array(); $player_female_arr = array();
        foreach(
$player_counts as $player_count)
        {
            if (
$player_count['player_sex_male'] == '1')
            {
                
$player_male_arr[] = $player_count['player_sex_male'];
            }
            elseif (
$player_count['player_sex_female'] == '1')
            {
                
$player_female_arr[] = $player_count['player_sex_female'];
            }
        }

        
$player_male array_sum($player_male_arr);
        
$player_female array_sum($player_female_arr);

        unset(
$player_male_arr); unset($player_female_arr);

        
$sql "UPDATE team SET
                player_male = '
$player_male',
                player_female = '
$player_female',
                WHERE team_id = '
$assoc_team_id'";
    }