Problem with i++

hello… i’m beginner, and i didn’t understand, why when i add i++ then all is in red or in blue color…
like
player1 (blue)
player2 (blue)
player3 (blue)
or
player1 (red)
player2 (red…

i need to get
player1 (blue)
player2 (red)
player3 (blue)
player4 (red…
here is code…

if ($players) foreach ($players as $player => $kills) {
# TRYING TO ADD ADDING i++ colors for all.. 
for ( $i = 0; $i < count( $players ); $i++ ) {
 $color = $i%2 ? 'blue' : 'red';
 }
 if ($player == "boxer") echo "<div style=\\"float:left;display:inline;color:$color\\">{$player}</div> <div style=\\"float:right;display:inline\\">admin</div>\
";
 
 else echo "<div style=\\"float:left;display:inline;color:$color\\">{$player}</div> <div style=\\"float:right;display:inline\\">[{$kills}]</div>\
";

}

You are only looping your color variable… if you do this you will see what is happening:


for ( $i = 0; $i < count( $players ); $i++ ) {
 $color = $i%2 ? 'blue' : 'red';
echo $color . '<br>';
}

But since you already have a foreach loop that goes through each entry… why not set it up like this?


 
if ($players) {

    $color = '';

    foreach ($players as $player => $kills) {
        
        // Switch the color
        if ($color == 'blue') {
            $color = 'red';
        }
        else {
            $color == 'blue'
        }

        // Boxer is an admin
        if ($player == "boxer") {
            $kills = 'admin';
        }

        // Output
         echo '<div style="float:left;display:inline;color:' . $color . '">' .$player . '</div>'
           . '<div style="float:right;display:inline">' . $kills . "</div>\
";
    }

}

Right now, you have a for loop inside the foreach loop, and all it does is loop through the entire players array and change the value of $color. So in the end if the number of values in $players is even, the color will always be blue, else it will always be red (or the other way around… :smiley: ).

Try this instead:


if ($players) 
  [B][COLOR="red"]$i == 0;[/COLOR][/B]
  foreach ($players as $player => $kills) {
[B][COLOR="Red"]    $color = $i%2 ? 'blue' : 'red';[/COLOR][/B]
    if ($player == "boxer") echo "<div style=\\"float:left;display:inline;color:$color\\">{$player}</div> <div style=\\"float:right;display:inline\\">admin</div>\
";
    else echo "<div style=\\"float:left;display:inline;color:$color\\">{$player}</div> <div style=\\"float:right;display:inline\\">[{$kills}]</div>\
";
    [B][COLOR="Red"]$i++;[/COLOR][/B]
  }

thanks!! :slight_smile: :slight_smile:
#3 worked…
Professionals…