PHP: Shorthand IF – ELSE Statement

Posted on Posted in Code Talk

The IF – ELSE statement in PHP has a shorthand version if you are comparing two values. A conditional operator “?:” (or ternary) operator is used to shorten this statement down to one line. The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

In variable example:

$variable = (statement) ? "return if true" : "return if false";

Example below:

<?php
   // Example usage for: Ternary Operator
   $action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
?>

The above is identical to this if/else statement

<?php
if (empty($_POST['action']))
{
   $action = 'default';
}
else
{
   $action = $_POST['action'];
}
?>

Seeing as this statement is one of the most used statement while programming, it is a handy one to remember!

Leave a Reply