11

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.

kgbph
  • 841
  • 1
  • 8
  • 26
  • empty() http://php.net/manual/en/function.empty.php – Mattia Dinosaur Aug 22 '18 at 04:02
  • @MattiaDinosaur It would still require me to use an `if` statement. – kgbph Aug 22 '18 at 04:04
  • try this $data->person->name->last_name or 'default' in my case it i sworking; – Dhruv Raval Aug 22 '18 at 04:24
  • Can you do something like this?: `if($data !== null && $data->person !== null && $data->person->name !== null) { echo 'not null'; }` – Edward Aug 22 '18 at 04:27
  • 1
    Possible duplicate of [Reference — What does this symbol mean in PHP?](https://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) – localheinz Aug 22 '18 at 06:00
  • @localheinz I am not asking for the symbol. I am asking if there is a null-conditional operator in PHP that will get the deep-nested property. – kgbph Aug 22 '18 at 06:05

3 Answers3

12

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';
Redr01d
  • 392
  • 2
  • 12
  • I noticed that PHP doesn't have `null-conditional` operator since a `null-coalescing` operator does the job. Thanks. – kgbph Aug 22 '18 at 05:35
  • Please note, that this does **not** work on methods, like a real null-conditional operator would – hakai Aug 01 '19 at 08:07
  • 1
    Actually, the null-coalescing operator `$result = $value ?? $default;` equals `$result = isset($value) ? $value : $default;` for `empty`, you would have to use `$result = $value ?: $default;` which is a shorthand for ternary operator `$result = $value ? $value : $default;` – MarthyM Sep 03 '19 at 14:50
7

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.

ya.teck
  • 2,060
  • 28
  • 34
1

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

Madhuri Patel
  • 1,270
  • 12
  • 24