0

If I wanted to create a foreach loop that would add every second player to team A or team B

foreach ( $selectedplayers as $selectedplayer ) {
        TeamA[] = $selectedplayer;
        $selectedplayer++;
        TeamB[] = $selectedplayer; 
}

I know I can do it with a for loop but was interested to see if it could be done this way.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
denski
  • 1,768
  • 4
  • 17
  • 35

1 Answers1

5

No. $selectedplayer is the actual value of each element. Either use your own counter:

$i = 0;
foreach ( $selectedplayers as $selectedplayer ) {
        if($i % 2 === 0)) {
            $TeamA[] = $selectedplayer;
        } else {
            $TeamB[] = $selectedplayer; 
        }
        $i++;
}

Or use the $key of the array if the keys are sequential (or at least odd, even pattern):

foreach ( $selectedplayers as $key => $selectedplayer ) {
        if($key % 2 === 0)) {
            $TeamA[] = $selectedplayer;
        } else {
            $TeamB[] = $selectedplayer; 
        }
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87