Reputation: 33
I can use ??
operator in PHP to handle an index of array which is not defined.
I am confused if null safe operator offers me same or extends ??
operator's functionality?
Edit:
I can do in existing PHP versions to check if there is a specific property is defined in the array:
$user_actions = ['work' => 'SEO','play' => 'Chess', 'drink' => 'coffee'];
$fourth_tag = $user_tags['eat'] ?? "n/a";
I am trying to understand whether null safe operator is offering me something better to do so?
Upvotes: 2
Views: 4078
Reputation: 339
Null coalescing operator (??
) work as an if statement it takes two values if first is null then it is replaced by second.
$a = null;
$b = $a ?? 'B';
Here $b
will get the value B
as $a
is null
;
In PHP8, NullSafe
Operator (?->
) was introduced will gives option of chaining the call from one function to other. As per documentation here: (https://www.php.net/releases/8.0/en.php#nullsafe-operator)
Instead of null check conditions, you can now use a chain of calls with the new nullsafe operator. When the evaluation of one element in the chain fails, the execution of the entire chain aborts and the entire chain evaluates to null.
Here is the example from documentation:
$country = null;
if ($session !== null) {
$user = $session->user;
if ($user !== null) {
$address = $user->getAddress();
if ($address !== null) {
$country = $address->country;
}
}
}
But in PHP8 you can simply do this:
$country = $session?->user?->getAddress()?->country;
So the working of both operators is significantly different.
Upvotes: 2