I realise this may be a generic php question, but as it’s related to WP I’m including it here.
If adding a simple conditional to my page.php template, do I need to include an ‘else’ (for other pages) and ‘endif’?
<?php
if (is_tree(39)) : get_template_part('templates/partial/menu-buy');
elseif (is_tree(117)) : get_template_part('templates/partial/menu-programs');
?>
Other than an ’empty condition’ (don’t know if that’s the right word) I can’t see a way to include an ‘else’ for other pages.
My limited knowledge suggests it’s probably good practice to finish with ‘endif’, but I’ve seen conditionals written with/without an ‘endif’ and hence wonder whether it’s necessary.
UPDATE: Thanks to those who’ve answered, I now realise there’s two different forms of syntax:
http://php.net/manual/en/control-structures.alternative-syntax.php
PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.
3 Answers
You just need an else block:
//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
}
Regarding “it’s probably good practice to finish with ‘endif'”, endif
is only used when you are using the templating syntax:
if():
//do stuff
endif;
the alternative is regular braces syntax:
if(){
//do stuff
}
The former is preferable when you are outputting html by dropping out of php with a closing php tag, because an endif
is easier to match up than a closing brace:
<?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 }?>
However when writting code that does not drop out of php mode, the latter is far more common and arguable easier to read:
$out=[];
if($someCondition){
$out[$username]=[];
foreach($someArray as $key => $value){
$out[$username][] = $key . ' : ' . $value;
}
}