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

王林
Release: 2023-08-20 11:22:02
forward
1242 people have browsed it

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;
Copy after login

Equivalent expression

if(condition) {
   return expression1;
}
else {
   return expression2;
}
Copy after login

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;
Copy after login

Equivalent expression

if(isset(variable)) {
   return variable;
}
else {
   return expression;
}
Copy after login

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>
Copy after login

Output

not passed
not passed
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!