开发者

Not sure the loop I need to use every two variables

I have a problem where I have an array $user.

I have $_SESSION['players'] which has the total amount of $user.

I need a function where I can take the user1 and 2开发者_开发问答 and use them. Then move on to user3 and 4 and use them, and so on.. until I have used all the players. Obviously the total $user[$i] would be players-1.

Anyone have a solution for this? Thanks


Would this suit your needs? This requires that there be an even number of players to work properly though, unless you stick in a check for odd numbers:

for ($i = 0; $i < $_SESSION['players']; $i += 2) {
    $userA = $user[$i];
    $userB = $user[$i + 1];

    // Do things with $userA and $userB variables...
}


just because you're taught how to use for loops in one way does not mean that you're stuck continuing to use them the way you were taught:

$length = count($users);

$length = $_SESSION['players'];
for ($i = 0; $i < $length; $i += 2)
{
  if (!isset($user[$i], $user[$i + 1])) break;
  $userOne = $user[$i];
  $userTwo = $user[$i+1];
  //do stuff
}


I realized that isset wasn't necessary, the for call could be modified more:

$length = $_SESSION['players'];
for ($i = 0; ($i + 1) < $length; $i += 2)
{
  $userOne = $user[$i];
  $userTwo = $user[$i+1];
  //do stuff
}

EDIT to change how the length was calculated:
EDIT to validate that user exists
EDIT to add consolidated version

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜