PHP Tutorials: Ternary & NULL Coalescing

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.

  1. Condition
  2. Statement if true
  3. Statement if false
(condition) ? statement if true : statement if flase
	$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.

	$day = isset($_GET['day']) ? $_GET['day'] : 'Not found!';
	$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.

Leave a Reply

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