kgbph
kgbph

Reputation: 901

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.

Upvotes: 13

Views: 4348

Answers (3)

ya.teck
ya.teck

Reputation: 2336

There is nullsafe operator since PHP 8.

$last_nam = $data?->person?->name?->last_name;

The advantage of nullsafe operator over null coalescing is that the former allows to specify exact parts of the chain that should be null-safe.

Upvotes: 10

Madhuri Patel
Madhuri Patel

Reputation: 1270

In PHP 7, a new feature, null coalescing operator (??) has been introduced. It is used to replace the ternary operation in conjunction with isset() function.

The Null coalescing operator returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

For your example:

$username = isset($data->person->name) ? isset($data->person->last_name) : 'not name';

Upvotes: 1

Redr01d
Redr01d

Reputation: 392

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';

Upvotes: 12

Related Questions