A lot of updates have come in PHP 7.4. One of them is null Coalesce Assignment Operator?? (=)
. This is used in combination with isset()
method to replace the null Coalesce operation. This operator is used for assigning its right-hand operand value to its left-hand operand only if the left-hand operand value is null.this update you can speed up work.
// Equivalent code using ternary operator
$username = isset($_GET['username']) ? $_GET['username'] : 'not body';
echo $username;
// Chaining ?? operation
$username = $_GET['username'] ?? $_POST['username'] ?? 'not body';
echo $username;
The Null Coalesce Assignment Operator(??=)
can now further simplify the above sentence as follows:
$_GET['username'] ??= 'no body';
Difference between Null Coalescing Operator and Ternary Operator
- Ternary Operator remains associative where as, Null Coalescing Operator is associative to the right.
- If left operand is null, Ternary Operator throws e-notice, while null coalescing operator does not throw e-notice if left operand does not exist.
- Ternary Operator checks if the value is valid even if the value is not null, the Null coalescing operator checks.
- If more iteration is needed to be done, the null coalescing operator found to be quicker than the ternary operator.
- Null coalescing operator offers comparatively improved readability as well.