
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
PHP 7 - Null Coalescing Operator
In PHP 7, a new feature, null coalescing operator (??) has been introduced. It is used to replace the ternary operation in conjunction with isset() function. The Null coalescing operator returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
Example
<?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/>"); // Chaining ?? operation $username = $_GET['username'] ?? $_POST['username'] ?? 'not passed'; print($username); ?>
It produces the following browser output −
not passed not passed not passed
Advertisements