Difference between the Ternary operator and Null coalescing operator in php

PHPServer Side ProgrammingProgramming

Ternary operator

Ternary operator is used to replace if else statements into one statement.

Syntax

(condition) ? expression1 : expression2;

Equivalent Expression

if(condition) {
   return expression1;
}
else {
   return expression2;
}

If condition is true, then it returns result of expression1 else it returns result of expression2. void is not allowed in condition or expressions.

Null coalescing operator

Null coalescing operator is used to provide not null value in case the variable is null.

Syntax

(variable) ?? expression;

Equivalent Expression

if(isset(variable)) {
   return variable;
}
else {
   return expression;
}

If variable is null, then it returns result of expression.

Example

<!DOCTYPE html>
<html>
<head>
   <title>PHP Example</title>
</head>
<body>
   <?php
      // fetch the value of $_GET['user'] and returns 'not passed'
      // if username is not passed
      $username = $_GET['username'] ?? 'not passed';
      print($username);
      print("<br/>");
      // Equivalent code using ternary operator
      $username = isset($_GET['username']) ? $_GET['username'] : 'not passed';
      print($username);
      print("<br/>");
   ?>
</body>
</html>

Output

not passed
not passed
raja
Published on 06-Jan-2020 10:45:23
Advertisements