PHP Shorthand of If else Ternary operator

0
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

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

if($value == 'blue')
{
 echo 'Color is Blue';
}
else
{
 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)

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

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

PROS :

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

CONS : 

  • Little confusing
  • Hectic for more conditions

Leave a Reply

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

25  −  21  =