繁体   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