Franscape Development Tutorials
You are currently viewing the Ternary Operator Statements tutorial, in the 'PHP' category.
-----------------

The use of Ternary Operators allows for nothing more than a cleaner, safer method of writing if...else statements, especially when placing statements inside other statements.

Take, for example, standard If/Else premises:

Code:
<?php

if ($var == "value1" || !$_REQUEST['action']){
$text = "STATEMENT1"; // if condition returns true
} else {
$text = "STATEMENT2"; // if codition returns false
}
echo($text);

?>


In verbal form, the above code is executed as follows:

If the variable, $var, equals the invariant, value1 -- OR if action is not defined in the header as a HTTP Function -- STATEMENT1 is echoed. Conversely, if the condition returns false instead ( ... $var != "value1" || isset($_REQUEST['action']) ...) STATEMENT2 is echoed.

No problem.

However, yes, there is another way of writing this - we use the following general syntax for Ternary Operator statements:

Code:
$output_var = (condition) ? Rslt_if_True : Rslt_if_False;


Um, what? Let me explain.

The condition is being submitted for proof testing, hence the first conditional or ternary operator -- the question mark ("?") -- that immediately follows it. This operator preceeds the value of the output variable, $output_var, if the condition is TRUE - Rslt_If_True.

If the condition returns false, $output_var equals the portion of the string that follows the second ternary operator (the colon, ":") - Rslt_If_False.

Let's apply our initial example to the ternary operator syntax:

· $output_var = $text
· (condition) = ($var == "value1" || !$_REQUEST['action'])
· Rslt_If_True = STATEMENT1
· Rslt_If_False = STATEMENT2

Ergo, our initial if...else statement may be written as follows:

Code:
<?php
$text = ($var == "value1" || !$_REQUEST['action']) ? STATEMENT1 : STATEMENT2;
echo($text);
?>


For those who have not yet been scared away, we will continue with "stacked" ternary operator statements (where one statement is placed inside another).

Firstly, our standard if...else statement:

Code:
<?php
$var = 2;
$global_var = "value1";

if($global_var == "value1"){
$result = 2;
} else {
$result = 3;
}

if ($var == $result){
$text = "STATEMENT1"; // if condition returns true
} else {
$text = "STATEMENT2"; // if codition returns false
}
echo($text);

?>


Alas, we have two if/else statements, where the output of the latter is a direct (and dependent) function of the former's. Yuck.

The stacked statements, in ternary syntax, are written as follows:

Code:
<?php
$var = 2;
$global_var = "value1";

$text = ($var == (($global_var == "value1") ? 2 : 3)) ? STATEMENT1 : STATEMENT2;
echo("$text");
?>


-----------------
· Discuss this and other tutorials on the FS Forums.
· Return to the PHP tutorial listing.
· Return to the Tutorial Overview.
· Return Home.
Back.
Sponsored Links - Register and/or Login to remove it