我有一大组if语句,当其中一个为true时,下面的if语句就不需要测试了。
我不知道最好的方法是什么。
我应该创建一个函数、开关还是while循环?
每个连续的if语句都是不同的,并且具有预先创建的输入值。我将尝试创建一个简单的例子来更好地解释这一点。
$total = ($val1+$val2+$val3)/$arbitaryvalue
if($total > 2){//Do Something
}
$total = ($val1+$val2)/$anothervalue
if($total > 2){//Do Something different
}
将它们放入上一个if语句的else中,这意味着只有在第一个条件计算为false时才运行。如果你有很多if语句,这会变得很混乱,但是,你问题中的例子代表了你的需求规模吗?
$total = ($val1+$val2+$val3)/$arbitaryvalue
if($total > 2){//Do Something
}
else
{
$total = ($val1+$val2)/$anothervalue
if($total > 2){//Do Something different
}
}
if ( condition ) {
}
else if ( another_condition ) {
}
...
else if ( another_condition ) {
}
etc
决定是否使用循环将取决于实际示例。如果$total是如何设置的,那么我们可以使用循环。如果没有,最好只做连续的If语句:
if(($val1+$val2+$val3)/$arbitraryvalue > 2){
//Do Something
}
else if(($val1+$val2)/$anothervalue > 2)
{
//Do something different
}
但是,如果$val1+$val2和$anothervalue部分有一个模式,那么循环可能是更好的解决方案。在我看来,你的决定也应该取决于这种模式是否合理。
由于使用else
既没有好处,也很难维护,因此我建议使用一个函数。
函数会更理想,因为一旦使用return
满足条件,就可以随时退出函数。
如果从函数中调用,return语句将立即结束当前函数的执行,并将其参数返回为函数调用的值。
以下是一个示例函数,其中设置了用于演示的伪值:
<?php
function checkConditions(){
$val1 = 5;
$val2 = 10;
$val3 = 8;
$arbitaryvalue = 5;
$anothervalue = 4;
$total = ($val1+$val2+$val3) / $arbitaryvalue;
if($total > 2){
return 'condition 1';
}
$total = ($val1+$val2) / $anothervalue;
if($total > 2){
return 'condition 2';
}
return 'no conditions met';
}
echo checkConditions();
?>
如果您想执行注释代码中指示的某种类型的操作,那么您可以在从函数返回之前执行适当的操作。
Ben Everard说的是正确的方法,但还有许多其他解决方案:
$conditions = array(
array(
'condition' => ($val1+$val2+$val3)/$arbitaryvalue,
'todo' => 'doSomething',
),
array(
'condition' => ($val1+$val2)/$arbitaryvalue,
'todo' => 'doSomethingDifferent',
),
// ...
);
foreach ($conditions as $item)
{
if ($item['condition'])
{
// $item['todo']();
call_user_func($item['todo']);
break;
}
}
function doSomething()
{
// ...
}
function doSomethingDifferent()
{
// ...
}