Joshua Leung
Joshua Leung

Reputation: 2399

Is there a way to combine ternary operator with null coalescing?

I would like to check if a variable is null or not first, if null, return 'Null'. Else, check if the variable is === 1, if so, return 'Yes, else, return 'No'.

Right now I have this:

($is_realtor ? 'Yes' : 'No') ?? 'Null'

But it seems like it will never reach the null coalescing operator. It will return 'No' even if $is_realtor is null.

Is there a concise and elegant way to combine them?

Upvotes: 2

Views: 909

Answers (1)

Ebby
Ebby

Reputation: 534

You can put together as many conditions as you want. But it will become hard to read the more you nest.

$value = ($is_realtor === null ? null : ($is_realtor == 1 ? 'yes':'no') ); 

Upvotes: 2

Related Questions