 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference between the Ternary operator and Null coalescing operator in php
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
Advertisements
 