DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Securing Your Software Supply Chain with JFrog and Azure
Register Today

Trending

  • Azure Virtual Machines
  • How to Use an Anti-Corruption Layer Pattern for Improved Microservices Communication
  • Top 10 Pillars of Zero Trust Networks
  • Unlocking Game Development: A Review of ‘Learning C# By Developing Games With Unity'

Trending

  • Azure Virtual Machines
  • How to Use an Anti-Corruption Layer Pattern for Improved Microservices Communication
  • Top 10 Pillars of Zero Trust Networks
  • Unlocking Game Development: A Review of ‘Learning C# By Developing Games With Unity'

Tips & Tricks of Learning Ternary Operators

David Walsh user avatar by
David Walsh
·
Mar. 17, 08 · News
Like (1)
Save
Tweet
Share
18.99K Views

Join the DZone community and get the full member experience.

Join For Free

I started using ternary operator logic about six months ago and notice myself using shorthand if/else logic all the time. It shortens my code, the time to write it, and makes me look smarter to the mustaches.

Thanks to Google Analytics, I've found that I receive many page views from programmers looking for information on "shorthand if/else", "ternary logic", and "shorthand logic php". I've created a few guidelines for "?:" rookies to make learning shorthand if/else as quick and easy as it should be.

Start With If/Else, Then Convert To Ternary

Start with your expressions in simple if/else code, and then carefully convert each if/else into a shorter ternary statement. It may help to take the additional step of creating variables for each expression.

/* start with if / else ... */
if($language == 'php')
{
$dynamic = true;
}
else
{
$dynamic = false;
}

/* ... then convert */
$dynamic = ($language == 'php' ? true : false); //or 1 : 0

/* optional code shortening */
$dynamic = $language == 'php';

Use Parenthesis To Group Logic

Keeping your expressions in parentheses is a great way to keep your code organized for later maintenance.

//viva grouping!
$age_code = ($age > 10 ? ($age > 20 ? ($age > 30 ? 'senior' : 'adult') : 'teen') : 'youngster');

//the following isn't as fun to read
$age_code = $age > 10 ? $age > 20 ? $age > 30 ? 'senior' : 'adult' : 'teen' : 'youngster';

Use "Intermediate" Variables For Parts of the Expression

The above 10/20/30 code is rough and can be difficult to maintain. Using variables may help simplify things.

//better?
$over_30 = ($age > 30 ? 'senior' : 'adult');
$over_20 = ($age > 20 ? $over_30 : 'teen');
$age_code = ($age > 10 ? $over_20 : 'youngster');

Use True/False Boolean, Not Just The Expression

As you probably know, you can use JUST the expression as the return value. If you believe that will hurt you during the learning process, explicitly return true or false.

/* explicit */
$can_drive = ($age >= 16 ? true : false);

/* implicit, just the expression */
$can_drive = $age >= 16;

Know When Not To Use Ternary Logic

If there are many nested if/else statements in the logic, shorthand expressions may not be the best option. For example, the following snippet of code returns whether a given year is a leap year:

$is_leap_year = ((($year % 4) == 0) && ((($year % 100) != 0) || (($year %400) == 0)));

The above code works well for ternary logic because it wont have to be updated frequently — the leap year "calculation" is always the same. If you have code that needs to be updated often, shorthand if/else may not be the optimal choice.

Test! Test! Test!

As with any type of programming, test early and often!

Operator (extension)

Published at DZone with permission of David Walsh. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Azure Virtual Machines
  • How to Use an Anti-Corruption Layer Pattern for Improved Microservices Communication
  • Top 10 Pillars of Zero Trust Networks
  • Unlocking Game Development: A Review of ‘Learning C# By Developing Games With Unity'

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: