如何在while循环中运行函数,直到它返回true?

时间:2018-02-09 21:23:43

标签: php arrays

我认为我编写的代码本身试图使其工作是非常自我解释的。我第一次使用while循环时,我确实搜索了其他类似的问题,还here但我无法解决这个问题。

现在,代码只出于某种原因运行一次,如果对于某些随机机会,array_rand中的数字为6则返回,否则它甚至不会回显什么时候应该,因为它在while循环中,但显然我错了。

/**
* Check if param number is between 5 and 7
* @param {int} $number - number
*/
function check($number){
  if($number >= 5 && $number <= 7){
    return array('message' => 'Number is between the min and the max');
  }

  return false;
}

// Random numbers for testing 
$info = array(1,2,3,4,5,6,7,8,9,10);

// Get a random number from the array
$info_rand = $info[array_rand($info)];

// run function by passing a random number from the array
$run_loop = check($info_rand);

// here we should keep running the function until it returns true then break, otherwise just echo no so we know it's running
while(true){
  if($run_loop){
    echo 'Yes';
    break;
  } else {
    echo 'no';
  }
}

https://eval.in/953478

2 个答案:

答案 0 :(得分:2)

看看以下变化:

/**
* Check if param number is between 5 and 7
* @param {int} $number - number
*/
function check($number){
  if($number >= 5 && $number <= 7){
  return array('message' => 'Number is between the min and the max');
 }

 return false;
}


// Random numbers for testing 
$info = array(1,2,3,4,5,6,7,8,9,10);
// here we should keep running the function until it returns true then 
// break, otherwise just echo no so we know it's running
while(true){

   // Get a random number from the array
   $info_rand = $info[array_rand($info)];

   // run function by passing a random number from the array
   $run_loop = check($info_rand);
   if($run_loop){
     echo 'Yes';
     break;
   } else {
    echo 'no';
   }
}

答案 1 :(得分:1)

什么都没有改变$ run_loop变量

/**
* Check if param number is between 5 and 7
* @param {int} $number - number
*/
function check($number){
  if($number >= 5 && $number <= 7){
    return array('message' => 'Number is between the min and the max');
  }

  return false;
}

// Random numbers for testing 
$info = array(1,2,3,4,5,6,7,8,9,10);

// here we should keep running the function until it returns true then break, otherwise just echo no so we know it's running
while(true){
  //this will randomize each time
  //before it would never change
  if(check($info[rand(0,count($info))])){
    echo 'Yes';
    break;
  } else {
    echo 'no';
  }
}