如何执行相同的操作,直到达到一个条件


How to do the same operation until it reaches one condition

如何执行相同的操作直到达到一个条件?例如:

<?php
  $n = rand(5,157);
  if ($n=='63'){
    echo 'ok';
  } else {
    //* another random, until rand () will give 63  *//
  }
?>

我该如何解决这个问题?提前感谢!

你需要使用 while 循环:

<?php
  $n = rand(5,157);
  while ($n != 63) {
    $n = rand(5,157); // n is not 63, get another number
  }
  echo 'ok';
?>

if将检查一次条件,而while将检查条件,直到它不true

在循环时查看 PHP。 我们希望继续生成一个随机数,而最后一个不等于 63。 所以使用:

$n = rand(5,157);
while($n != 63){
    $n = rand(5,157);
}
echo "ok";

因此,$n设置为初始值,每个while循环都会生成一个新值$n然后检查它。 当n=63时,循环中断并回显"ok"。