The Null coalesce operator (??) returns the result of its first operand if it exists and is not NULL, or else it will return its second operand. Using this operator like $_GET[‘mykey’] ?? “” will not raise an E_NOTICE, and can be safely used.
So, instead of using isset and ternary operator (?:) we can just use the Null Coalesce Operator (??). Here is an example usage:
So, instead of using isset and ternary operator (?:) we can just use the Null Coalesce Operator (??). Here is an example usage:
// Fetches the value of $_GET['user'] // and returns 'nobody' if it does not exist. $username = $_GET [ 'user' ] ?? 'nobody' ; // This is equivalent to: $username = isset( $_GET [ 'user' ]) ? $_GET [ 'user' ] : 'nobody' ; |
We can also chain the Null Coalesce operator. Here is an example:
// This will return the first defined value out of // $_GET['user'], $_POST['user'], and 'nobody'. $username = $_GET [ 'user' ] ?? $_POST [ 'user' ] ?? 'nobody' ; |
More examples and difference from ternary operator
// This will make the value of $action to be 'none'. // This is because the first operand is null. $action = null ?? 'none' ; // Ternary Operator, value will be 12 $action = false ?: 12; // Null Coalesce Operator, value will be false. // This is because the first operator exists and is not null. $action = false ?? 'none' ; |
Here are a few more examples from PHP RFP for Null Coalesce Operator
// Calls a hypothetical model-getting function, // and uses the provided default if it fails $model = Model::get( $id ) ?? $default_model ; // This is equivalent to: if (( $model = Model::get( $id )) === NULL) { $model = $default_model ; } // Parse JSON image metadata, and // if the width is missing, assume 100 $width = $imageData [ 'width' ] ?? 100; // This is equivalent to: $width = isset( $imageData [ 'width' ]) ? $imageData [ 'width' ] : 100; |
This example demonstrates the precedence relative to the ternary operator and the boolean or operator, which is the same as C#:
var_dump(2 ?? 3 ? 4 : 5); // (2 ?? 3) ? 4 : 5 => int(4) var_dump(0 || 2 ?? 3 ? 4 : 5); // ((0 || 2) ?? 3) ? 4 : 5 => int(4)
|
(condition) ? /* value to return if condition is true */
: /* value to return if condition is false */ ;
syntax is not a "shorthand if" operator (the
?
is called the conditional operator) because you cannot execute code in the same manner as if you did:if (condition) {
/* condition is true, do something like echo */
}
else {
/* condition is false, do something else */
}
In your example, you are executing the
echo
statement when the $address
is not empty. You can't do this the same way with the conditional operator. What you can do however, is echo
the result of the conditional operator:echo empty($address['street2']) ? "Street2 is empty!" : $address['street2'];
and this will display "Street is empty!" if it is empty, otherwise it will display the street2 address.
No comments:
Post a Comment