The Ternary Operator
In addition to if..else statement PHP also provide a shorthand conditional operator which is called the ternary operator or the conditional ternary operator. Ternary mean composed of three parts which clearly means the ternary operator takes 3 parameters.
- Statement if true
- Statement if false
Syntax: <?php (condition) ? statement if true : statement if flase ?>
<?php $a = 10; $b = 15; echo ($a < $b) ? "$b is greater than $a.": "$a is great than $b"; // OUTPUT: 15 is greater than 10 ?>
The Null Coalescing Operator
A new operator has been Introduced by PHP7 and it’s another shot and operator for the conditional ternary operator. This operator can be used against a null value. Let’s take an example to see the difference between a conditional ternary operator and the Null coalescing operator.
<?php $day = isset($_GET['day']) ? $_GET['day'] : 'Not found!'; ?>
<?php $day = $_GET['day'] ?? 'Not found!'; ?>
If the PHP script finds the value in that $_GET[‘day’] it will assign $_GET[‘day’] value to the variable $day and in case it does not find any value it will assign “not found” to it.