Site icon WP Smith

PHP Tertiary Operator and Complex Conditional Assignment: Variable = Condition ? True Statement : False Statement

If you've been dealing with WordPress or PHP, more than likely you have seen the Ternary Operator in a statement. If you were like me, when you saw it for the first time, you had no idea what sort of assignment statement it was except possibly a conditional assignment. So what is it? The Ternary Operator is an operator that takes three (3) arguments: Condition, True Statement, and False Statement. So a complex conditional assignment is the same as a ternary operator but with more than three (3) arguments.

From Wikipedia: Ternary Operation:
[php]if ($a > $b) {
$result = $x;
} else {
$result = $y;
}
[/php]

Rewritten using the ternary operator:
[php]$result = ($a > $b) ? $x : $y;[/php]

So,
[php]$my_var = ($var1 > $var2) ? /*simple true statement */ : /*simple false statement */; [/php]

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

// The above is identical to this if/else statement
if (empty($_POST['action'])) {
$action = 'default';
} else {
$action = $_POST['action'];
}

?>
[/php]

To create a switch-like conditional assignment as demonstrated in Wikipedia: Conditional Assignment ?:
[php]<?php
$arg = "T";
$vehicle = ($arg == 'B') ? 'bus' :
(($arg == 'A') ? 'airplane' :
(($arg == 'T') ? 'train' :
(($arg == 'C') ? 'car' :
(($arg == 'H') ? 'horse' :
'feet'))));
echo $vehicle;
?>
[/php]