您只需要一个else块:
//templating syntax
if($condOne):
//do stuff if $condOne is true
elseif($condTwo):
//do stuff if $condOne is false and $condTwo is true
else:
//do stuff if both $condOne and $condTwo are false
endif;
//braces syntax
if($condOne){
//do stuff if $condOne is true
}elseif($condTwo){
//do stuff if $condOne is false and $condTwo is true
else{
//do stuff if both $condOne and $condTwo are false
}
关于“以‘endif’结尾可能是一种好的做法”,
endif
仅在使用模板语法时使用:
if():
//do stuff
endif;
另一种方法是常规大括号语法:
if(){
//do stuff
}
在输出html时,最好使用关闭的php标记退出php,因为
endif
比右括号更容易匹配:
<?php if($someCondition):?>
<h1>Hello <?=$userName?>, how are you today?</h1>
<ul>
<?php foreach($someArray as $key => $value):?>
<li><?=$key?> : <?=$value?></li>
<?php endforeach;?>
</ul>
<?php endif;?>
VS:
<?php if($someCondition){?>
<h1>Hello <?=$userName?>, how are you today?</h1>
<ul>
<?php foreach($someArray as $key => $value){?>
<li><?=$key?> : <?=$value?></li>
<?php }?>
</ul>
<?php }?>
但是,在编写不退出php模式的代码时,后者更常见,更易于阅读:
$out=[];
if($someCondition){
$out[$username]=[];
foreach($someArray as $key => $value){
$out[$username][] = $key . \' : \' . $value;
}
}