Home  >  Article  >  Backend Development  >  In php, what is the difference between ternary operator and null coalescing operator?

In php, what is the difference between ternary operator and null coalescing operator?

王林
王林forward
2023-08-20 11:21:111258browse

In php, what is the difference between ternary operator and null coalescing operator?

Ternary Operator

The ternary operator is used to replace an if else statement with a single statement.

Syntax

(condition) ? expression1 : expression2;

Equivalent expression

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

If the condition is true, return the result of expression 1, otherwise return the result of expression 2. void is not allowed in conditions or expressions.

Null Coalescing Operator

The null coalescing operator is used to provide a non-null value when the variable is empty.

Syntax

(variable) ?? expression;

Equivalent expression

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

If the variable is empty, the result of the expression is returned.

Example

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

Output

not passed
not passed

The above is the detailed content of In php, what is the difference between ternary operator and null coalescing operator?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete