PHP Do-While循环

时间:2016-01-19 18:45:04

标签: php

以下是我未完成的代码。最后一点决定抛出无限循环。我正在尝试创建一个随机数字脚本,不会重复7个随机选择中的数字。似乎一旦我在脚本开始循环的最后一行添加了||。谁能告诉我我做错了什么?

<?php 

$n1 = rand(1, 12);
$n2 = rand(13, 21);
$n3 = rand(15, 27);
$n4 = rand(20, 38); 
$n5 = rand(30, 46);
$n6 = rand(39, 49);
$bo = rand(1, 49);

// First number
echo $n1 . " ";

// Second number
do {
    echo $n2 . " ";
} while ($n1 == $n2);

// Third Number
do {
    echo $n3 . " ";
} while ($n3 == $n2 || $n1);

?>

6 个答案:

答案 0 :(得分:2)

$n1总是与0不同

do {
    echo $n3 . " ";
} while ($n3 == $n2 || $n1);  //<-- allways true

答案 1 :(得分:2)

@Majid所说的是正确的。检查PHP's operator precedence

==运算符在||运算符之前执行,因此只要$n1不是false - y,循环就不会退出。

答案 2 :(得分:1)

不确定您到底要做什么,但最后一次执行while循环配置不正确。以下更正确,不会给你一个无限循环。

do {
 $n3 = rand(15, 27);
 echo $n3 . " ";
} while (($n3 == $n2) || ($n3 == $n1));

答案 3 :(得分:0)

这里有很多问题,但这是一条正确的道路。评论是内联的。

<?php 

$n1 = rand(1, 12);
$n2 = rand(13, 21);

// First number
echo $n1 . " ";

// Second number
// no loop needed as your rand doesn't overlap your $n1
echo $n2 . " ";

// Third Number
do {
    $n3 = rand(15, 27); // this needs to be in your loop so when its the same it will generate a new number
} while ($n3 == $n2) // your || isn't needed as it can't over lap your $n2

echo $n3 . " ";

// Fourth Number
do {
    $n4 = rand(20, 38); // this needs to be in your loop so when its the same it will generate a new number
} while ($n4 == $n3)

echo $n4 . " ";

// ... repeat 

// Seventh Number
do {
    $bo = rand(1, 49); // this needs to be in your loop so when its the same it will generate a new number
} while ($bo == $n1 || $bo == $n2 || $bo == $n3 || $bo == $n4 || $bo == $n5 || $bo == $n6) // use your || to check against all of your variables

echo $bo;

?>

答案 4 :(得分:0)

是的 - 马吉德是对的,这将永远是一个无限循环。您可能想要的是类似于:

$previousNums = array();

for ($i = 0; $i < 7; $i++)
{
  $try = rand(0, 49);
  while (in_array( $try, $previousNums ) ) {
    // means we have already used this num, so try again
    $try = rand(0, 49);
  } 
  // append this num in the list of previousNums
  $previousNums[] = $try;

  echo ' num = ' . $try;
}

答案 5 :(得分:-1)

||的优先级低于==所以实际上它更像是这样:

while(($n3 == $n2)||$n1))

我觉得这不是你想要的,所以把它改成

while(($n3 === $n2)||($n3 === $n1))

请记住使用===进行比较。

我希望它有所帮助