What is Ternary Operators in PHP

A ternary operator can be used as a slightly faster, cleaner way to write simple if/else statements.

Let’s take a basic if/else statement…

if ($cake == "fresh") {
print "Yum yum! This cake is tasty.";
} else {
print "Yuck! This cake tastes awful!";

The above statement works like this:

If $cake is fresh, print “Yum yum! This cake is tasty.”. If it’s not fresh, print “Yuck! This cake tastes awful!”.

Using a ternary operator we can rewrite this statement in a much simpler form.

We would write it like:

$message = ($cake = "fresh") ? "Yum yum! This cake is tasty." : "Yuck! This cake tastes awful!";
print $message;

In case you’re not sure how that works, there are 3 parts to the ternary assignment:

$variable = condition ? if true : if false

The part to the left of the ? is the condition we’re testing.
The part between the ? and the : is what happens if the condition is true.
The part after the : is what happens if the condition is false.

Hopefully that makes sense and you can now start saving a bit of time by using ternary operators in your PHP scripting!

Written by 

2x Salesforce MVP | Platform Champion | 18x Salesforce Certified | MuleSoft Certified | 8x Trailhead Ranger | TechForce Services | Sydney | Australia

Leave a Reply

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