Home > Tutorials > PHP Tutorials > The PHP Ternary Operator

The PHP Ternary Operator

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:

if ($positions > 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:

$title = "Search " . ($positions > 1 ? : "Results" : "Result");

Much quicker isn’t it?

About 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.

Check Also

Installing Gnome Software Center on a Chromebook

Linux is pretty much all the rage these days when it comes to Chromebooks – ...

Like every other website, this site uses cookies to analyze our traffic. Cookies may also be utilized by our advertisers and partners. By using this website you agree to the use of said cookies. More Information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings, continuing to navigate past this message, or you click "Accept" below then you are consenting to the use of cookies on the Rapid Purple website.