简体   繁体   English

如果条件为真执行代码,否则使条件为真

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

I want to execute the code if the condition is true, else make the condition true and then execute the same code.. 如果条件为真,我想执行代码,否则使条件为真,然后执行相同的代码。

My code is.. 我的代码是..

$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....
}

I already use with goto , can you suggest any alternative solution. 我已经与goto一起使用,您可以建议任何替代解决方案。

I think the problem is simple bu I can't make a solution. 我认为问题很简单,但是我无法解决。

How can I do this...Any help is great... 我该怎么办...任何帮助都很棒...

TRY THIS 尝试这个

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

Try this: 尝试这个:

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

Your if condition is useless if you want this 您的if条件是无用的,如果您想要这个

I want to execute the code if the condition is true, else make the condition true and then execute the same code.. 如果条件为真,我想执行代码,否则使条件为真,然后执行相同的代码。

All you need is 所有你需要的是

$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

That is because you are providing both the values for the condition. 这是因为您要提供条件的两个值。 Whats the point in rand then? 那么rand什么意义呢? You know which value you want to select, rand is unnecessary. 您知道要选择哪个值,不需要rand

The other answers do give you a workaround to what you want to do but they don't notice the basic premise and requirement of the question itself is wrong. 其他答案确实为您提供了一种解决方法,但是他们没有注意到问题本身的基本前提和要求是错误的。

What's the point in saying keep finding a random value until the random value is 7? 继续寻找随机值直到随机值为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....
}

Just use this: 只需使用此:

$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