如果条件为true,我想执行代码,否则将条件设为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条件是无用的
如果条件为true,我想执行代码,否则将条件设为true,然后执行相同的代码。。
你只需要
$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