Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a null-conditional operator in PHP?

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.

like image 269
kgbph Avatar asked Aug 22 '18 03:08

kgbph


People also ask

What is NULL conditional?

?. 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 .

What is null coalescing operator in PHP?

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.

What is a null safe operator?

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.


1 Answers

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';
like image 118
Redr01d Avatar answered Nov 14 '22 20:11

Redr01d