简体   繁体   中英

Ternary operator shorthands ?? and ?:

I sometimes have code where I don't care if something is set, "false", "empty", "0" or "null". I just want to display its content and something else if there is no content (for whatever reason). I usually do something like that:

echo isset($a) && $a ? $a : 'something else';

It seems that with ternary shorthands, I can do something like this for "empty", "false", "null":

echo $a ?: 'something else';

But it does not work if $a is not set. So I can do something like this:

echo $a ?? 'something else';

But it will display an empty string if $a is empty. Is there a trick or a shorthand to simplify my code? (display "something else" only if it's set and not empty-false-null).

Example of use-case: with parsing JSON, you can have no value, no key or no content for an entry and it does not matter, you have to process it the same way. So same thing if empty, not set, false or null

?? indeed only does null coalescing, it does not consider truthiness .
?: on the other hand doesn't catch undefined variable errors.

The only simplification I see here is your use of isset($a) && $a ; that's exactly what the empty language construct is for:

echo !empty($a) ? $a : 'something else';

Having said that, you shouldn't have a lot of undefined variables in the first place, that's bad coding. You seem to be mostly concerned about array keys, in which case a small helper function is probably the best course of action:

echo get($a, 'key', 'something else');

I'm leaving the implementation as an exercise for the reader.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM