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 

I am Sakthivel Madesh, a certified Salesforce Advanced Developer & Administrator working on Salesforce Technology since 2011. I am currently working in Techforce Services as Sr. Salesforce Developer. I have worked on multiple technologies Like PHP, Java, Salesforce, I am very passionate about Salesforce and to earn 15x Salesforce Certification. I love Trailhead for learning Salesforce Skill and Become a Trailhead 5x Ranger too. I Love to Learn & Share my Salesforce knowledge to Salesforce Learners/Beginner using My Blog and Salesforce Community.

Leave a Reply