PHP Shorthand of If else Ternary operator

php if else shorthand

PHP Shorthand Of If else ( Ternary operator )

In this tutorial we are going to understand how we can write PHP if else in short form. This will help in many cases.

Lets start with an example :

Regular code of If else

$value = trim($_GET['color']);

if($value == 'blue')
 echo 'Color is Blue';
 echo 'Color is not Blue';

When we paas any color value in $value variable it will check if value is ” blue ” or not. And will echo text as per condition.

Lets do same with Shorthand ( Ternary operator)

echo trim($_GET['color'] == 'blue') ? "Color is Blue" : "Color is not Blue";

So here we re-write same above code in just one line.


  • Take less lines in codes .
  • Light weight code.


  • Little confusing
  • Hectic for more conditions

Leave a Reply

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

25  −  21  =