The PHP Ternary Operator

This is a great way to shorten simple if/else statements in PHP

It is possible to use the Ternary Operator syntax to shorten this down to 1 line:

if ($monkeySize === 'big') {
  $monkeyName = 'Chunky';
} else {
  $monkeyName = 'Funky';

Now, this is no doubt fairly common in your applications – a simple comparison determining the value of a variable. This can feasibly be rewritten for one line and still be easily understandable:

$monkeySize = 'big';
$monkeyName = ($monkeySize === 'big' ? 'Chunky' : 'Funky');
echo "He is a $monkeyName monkey!"; // He is a Chunky monkey!

Even someone who does not know about the Ternary Operator would be able to understand this without too much trouble and will hopefully appreciate the simplicity of the statement.

We can simplify the above code a bit further:

$monkeySize = 'slim';
echo 'He is a '.($monkeySize === 'big' ? 'Chunky' : 'Funky').' monkey!';
// He is a Funky monkey!

Be careful not to abuse the Ternary Operator by using it in complex or nested situations. You may frustrate yourself and others who have to decipher its meaning again later.


Leave a Reply

Your email address will not be published.

More Posts

How to use PHP Type Declarations

PHP has developed into a more strictly typed language in recent years. Type Declarations help with that and are a fairly new addition to PHP,


If you have come to JavaScript from a background in Java or C, then you will like the variation on the for loop. It is

Context Object Manipulation

One of the key concepts of JavaScript is the keyword this, which signifies the JavaScript context object. If you write an inner function, you can access

Polymorphic Functions

It is possible to define multiple functions with the same name in JavaScript, and the last one of those that you define will be the