The PHP Ternary Operator

The PHP Ternary Operator
Like the PHP if and switch statements, the ternary operator (?) allows your program to ask questions and perform tasks based on the answer to those questions. The PHP ternary operator looks like a question mark (?) and the code has three parts. Let's take a look at an example and discuss those parts.

(expression) ? return_if_ture : return_if_false;

$var = ($test_var == "December") ? "Merry Christmas" : "It is not Christmas yet";


($test_var == "December")
(expression)
The first part of the code is the text expression. In the example, it is tested if the variable ($test_var) is equal to "December". The test expression is placed on the left side of the ? ternary operator.

"Merry Christmas"
return_if_true
The second part of the code is returned only if the test expression is a match. If the $test_var is equal to December, the variable $var will be set to "Merry Christmas". This part of the code follows the ? ternary operator.

:
The colon : separates the second part of the code from the third part of the code.

"It is not Christmas yet"
return_if_false
The third part of the code will be returned if the test expression is not a match. In this case the variable $var will be set to "It is not Christmas yet". This part of the code follows the : colon.

;
The line of code is completed with the ; semicolon.

As you can see this type of code can only be used when there are just two alternatives to a situation. Therefore the code is not as versatile as the if and switch statements. But it is a concise way to code this type of situation.






This site needs an editor - click to learn more!



RSS
Editor's Picks Articles
Top Ten Articles
Previous Features
Site Map





Content copyright © 2023 by Diane Cipollo. All rights reserved.
This content was written by Diane Cipollo. If you wish to use this content in any manner, you need written permission. Contact BellaOnline Administration for details.