If else embedding inside html
What is the correct way of embedding if else and elseif conditions inside html?
I recommend the following syntax for readability.
<? if ($condition): ?>
<p>Content</p>
<? elseif ($other_condition): ?>
<p>Other Content</p>
<? else: ?>
<p>Default Content</p>
<? endif; ?>
Note, omitting php
on the open tags does require that short_open_tags
is enabled in your configuration, which is the default. The relevant curly-brace-free conditional syntax is always enabled and can be used regardless of this directive.
<?php if ($foo) { ?>
<div class="mydiv">Condition is true</div>
<?php } else { ?>
<div class="myotherdiv">Condition is false</div>
<?php } ?>
In @Patrick McMahon's response, the second comment here ( $first_condition is false and $second_condition is true ) is not entirely accurate:
<?php if($first_condition): ?>
/*$first_condition is true*/
<div class="first-condition-true">First Condition is true</div>
<?php elseif($second_condition): ?>
/*$first_condition is false and $second_condition is true*/
<div class="second-condition-true">Second Condition is true</div>
<?php else: ?>
/*$first_condition and $second_condition are false*/
<div class="first-and-second-condition-false">Conditions are false</div>
<?php endif; ?>
Elseif fires whether $first_condition is true or false, as do additional elseif statements, if there are multiple.
I am no PHP expert, so I don't know whether that's the correct way to say IF this OR that ELSE that or if there is another/better way to code it in PHP, but this would be an important distinction to those looking for OR conditions versus ELSE conditions.
Source is w3schools.com and my own experience.