I want to get the value of a deeply nested property.
e.g.
$data->person->name->last_name;
The problem is I am not sure if person
or name
is declared. I also don't want to use nested if
statements. If
statements won't look good for deeply nested properties.
Is there a null-conditional operator in PHP?
Solved
There is no need for a null-conditional
operator since a null-coalescence
operator does the job.
?. and ?() null-conditional operators (Visual Basic)Tests the value of the left-hand operand for null ( Nothing ) before performing a member access ( ?. ) or index ( ?() ) operation; returns Nothing if the left-hand operand evaluates to Nothing .
PHP 7 introduced a null-coalescing operator with ?? syntax. This operator returns its first operand if its value has been set and it is not NULL, otherwise it will return its second operand.
Null-safe operator is a new syntax in PHP 8.0, that provides optional chaining feature to PHP. The null-safe operator allows reading the value of property and method return value chaining, where the null-safe operator short-circuits the retrieval if the value is null , without causing any errors.
php7 Null coalescing operator doc
$user = $data->person->name->last_name ?? 'no name';
php 5.*
$user = !empty($data->person->name->last_name) ? $data->person->name->last_name :'no name';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With