The if() Control Structure

if() gives you a choice between outcomes you choose yourself. This gives you the most flexibility out of your projects.

Out of all the control structures, if() is probably one of the most used and has the most flexible ways of being written. Readability should be taken into account when you decide which way to write it. Using braces is the wisest since it doesn’t leave any room for error in what the author meant to include in the statement. if() statements may be written inside functions / methods, inside and outside most other control structures, procedural PHP, and HTML files.

if ( expr )


if ( expr ) {
} elseif ( expr ) {
} else {

The brace-less semicolon way is best for intermingling PHP with HTML. (i.e. view scripts from your MVC layout.) This way you can naturally write your HTML in your statements without having to use any quotes.

<?php if(expr) : ?>
    HTML Code 1
<?php else: ?>
    HTML Code 2
<?php endif; ?>

The Ternary (ter•na•ry) Operator is a special if() statement for small expressions. You can nest the ternary as many times as you would like, but more than once is usually frowned upon since your intentions will be unclear for other developers.

(expr1) ? (expr2) : (expr3);
(test for true) ? (do this if true) : (do this if false);
echo TRUE ? 'Yes, I am true' : 'I am not true';

prints: Yes, I am true

$value = FALSE ? 'Yes, I am true' : 'I am not true';
echo $value;

prints: I am not true


Sign up today to stay informed with industry news & trends