Posted Date:11-07-2017

In this post we will explain PHP ternary operator.

Example:

In this example we are using if else condition

<?php
$a=16;
if($a>18)
{
  echo "Eligible For Vote";
}
else
{
  echo "Not Eligible For Vote";
}
?>

In the above example $a value is greater than 18 eligible vote, Otherwise not eligible for vote.In this example we are using if condition,One more way to achieve result using php ternary operator.

Ternary Example

echo($a>18 ? 'Eligible For Vote':'Not Eligible For Vote');

Example 2:

In this example we are using nested if condition

<?php
$status=2;
if($status==1)
{
  echo "Stop";
}
elseif ($status==2) 
{
  echo "Ready";
}
else if($status==3)
{
  echo "Go";
}
else
{
  echo "Something went wrong";
}
?>

In the above example $status value is 1 then “Stop”, If the $status value is 2 then “Ready”, If the $status value is 3 then “Go”. one more way to achieve result using php ternary operator.

<?php
echo($status==1 ? 'Stop':($status==2 ? 'Ready' :($status==3 ? 'Go':'Something went wrong')));
?>

 

Leave a Reply