简体   繁体   中英

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.

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

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? You know which value you want to select, rand is unnecessary.

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?

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM