簡體   English   中英

如果條件為真執行代碼,否則使條件為真

[英]Execute code if condition is true else make the condition true

如果條件為真,我想執行代碼,否則使條件為真,然后執行相同的代碼。

我的代碼是..

$a = array(5,6,7,8,9);
$r = array_rand($a);
$b = 7;
if($b != $r)
  //do something
else
{
//here i want to select another random value and 
//execute the if else loop again until the if satisfies....
}

我已經與goto一起使用,您可以建議任何替代解決方案。

我認為問題很簡單,但是我無法解決。

我該怎么辦...任何幫助都很棒...

嘗試這個

$a = array(5,6,7,8,9);
$r = array_rand($a);
$b = 7;
while($b != $r)
{
  //do something
 $r = array_rand($a);
}

嘗試這個:

$a = array(5,6,7,8,9);
$b = 7;
$r = array_rand($a);
while($b != $a[$r]) {
    $r = array_rand($a);
}

您的if條件是無用的,如果您想要這個

如果條件為真,我想執行代碼,否則使條件為真,然后執行相同的代碼。

所有你需要的是

$a = array(5,6,7,8,9);
$b = 7;
$r=$b;  // That is exactly what your requirement is as it is stated.

//$r = $a[array_search($b,$a)];   this is also useless

這是因為您要提供條件的兩個值。 那么rand什么意義呢? 您知道要選擇哪個值,不需要rand

其他答案確實為您提供了一種解決方法,但是他們沒有注意到問題本身的基本前提和要求是錯誤的。

繼續尋找隨機值直到隨機值為7的意思是什么?

$a = array(5,6,7,8,9);
$r = array_rand($a);
$b = 7;
if($b != $r)
{
  //do something
echo $r;

}else
{
echo "select another random value";
//here i want to select another random value and 
//execute the if else loop again until the if satisfies....
}

只需使用此:

$a = array(5,6,7,8,9);
$b = 7;
$r = array_rand($a);

while($b != $r) {
    $r = array_rand($a);
}

  //do something

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM