PHP

PHP Ternary Operator

The ternary operator in PHP is used to write Conditional statements that work the same as if-else conditions the only difference between them is the syntax. The ternary operator takes less space in the code which makes the code more readable and easy to understand. 

It is also called the shorthand comparison operator in PHP because it has 3 parameters.

Syntax

(Condition) ? (Statement1) : (Statement2);

Or
 
Variable = (Condition) ? (Statement1) : (Statement2);

Parameter

  • Condition statement: in the condition statement we will set the condition on the behalf of Boolean values.
  • Statement_1: This statement will run if and only if the result is True. 
  • Statement_2: This statement will run if and only if the result is False.

As we mentioned above it works the same as the if-else conditions.

In the condition part, we write the condition that if this condition is True or False, then we use the operator “?” and then we write the statements which work like Do this Else this”.

We can assign it to a variable as well.

Example 1

<?php

$user_sign_in = true;

$title = $user_sign_in ? 'signout' : 'signin';

echo $title;

?>

In the above example, we declared a variable and set its value to true, then we used the ternary operator for checking the condition let’s check the results.

Output

Signout

As you can see the ternary operator gave the same result as if-else statements.

Example 2

<?php

  $x = 10;

  $y = $x < 25 ? 'greater' : 'less';

  echo ("Value of y is " . $y);

?>

Output

Value of y is greater

Example 3

<?php

  $age = 20;

  echo ($age >= 18) ? "Adult" : "kid";

?>

<br>

Output

Kid

Conclusion

In this tutorial, we discussed the PHP Ternary Operator and its examples and we saw how it works like if-else statements.

Leave a Comment