Open In App

Ternary operator vs Null coalescing operator in PHP

Ternary Operator

Ternary operator is the conditional operator which helps to cut the number of lines in the coding while performing comparisons and conditionals. It is an alternative method of using if else and nested if else statements. The order of execution is from left to right. It is absolutely the best case time saving option. It does produces an e-notice while encountering a void value with its conditionals. 



Syntax:

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

In ternary operator, if condition statement is true then statement1 will execute otherwise statement2 will execute. 



Alternative Method of Conditional Operation: 

if (Condition) {
    return Statement1;
} else {
    return Statement2;
}

Example: 




<?php
 
// PHP program to check number is even
// or odd using ternary operator
 
// Assign number to variable
$num = 21;
 
// Check condition and display result
print ($num % 2 == 0) ? "Even Number" : "Odd Number";
?>

Output:
Odd Number

Null coalescing operator

The Null coalescing operator is used to check whether the given variable is null or not and returns the non-null value from the pair of customized values. Null Coalescing operator is mainly used to avoid the object function to return a NULL value rather returning a default optimized value. It is used to avoid exception and compiler error as it does not produce E-Notice at the time of execution. The order of execution is from right to left. While execution, the right side operand which is not null would be the return value, if null the left operand would be the return value. It facilitates better readability of the source code. 

Syntax:

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

Alternative method of Conditional Operation: 

// The isset() function is used to take
// care that the condition is not NULL
if ( isset(Condition) ) {   
    return Statement1;
} else {
    return Statemnet2;
}

Example: 




<?PHP
 
// PHP program to use Null
// Coalescing Operator
 
// Assign value to variable
$num = 10;
 
// Use Null Coalescing Operator
// and display result
print ($num) ?? "NULL";
 
?>

Output:
10

Difference between Ternary operator and Null coalescing operator:


Article Tags :