The PHP Ternary Operator

Last Updated on: September 15, 2022

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.


Get notified of new posts:


Similar Posts

Leave a Reply

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