PHP has plenty of different operators, the majority of them being either unary or binary operators. A unary operator, such as !, performs its operations on just one single value. A binary operator, such as =, is used to perform an operation on two operads. So following the naming logic you’ve probably already figured out that a PHP ternary operator performs a single operation on three different values.

There is really only one ternary operator. The operator ? : is usually simply referred to as the “ternary operator” or “conditional operator”. It is used to test a Boolean condition and return one of two values. The construction consists of three parts: a Boolean condition before the question mark; a value between the question mark and the colon (which is returned if the condition is true); and lastly a value after the colon, (which is returned if the condition is false).

$a == 0 ? : "zero" : "not zero"

In this example, the first operant is the Boolean condition $a == 0. If this condition is found to be true, the operation returns the string “zero” ; otherwise it returns the string “not zero”. The first operand must always correspond to a Boolean value.

Basically – the ternary operator is a shortcut for an if/else statement. For example let’s take a look at the following if/else statement:

 1) {
$title = "Search Results";
} else {
$title = "Search Result";
}
?>

Can just as easily be replaced with the following ternary operator statement and the help of some concatenation:

 1 ? : "Results" : "Result");
?>

Much quicker isn’t it?

Published by Michael Boguslavskiy

Michael Boguslavskiy is a full-stack developer & online presence consultant based out of New York City. He's been offering freelance marketing & development services for over a decade. He currently manages Rapid Purple - and online webmaster resources center; and Media Explode - a full service marketing agency.

Leave a comment

Your email address will not be published. Required fields are marked *