简体   繁体   中英

Shorthand isset(), if not, return default value

I'm looking for a shorthand version of this code in PHP:

$address = isset($node->field_naam_adres['und'][0]['value']) ? $node->field_naam_adres['und'][0]['value'] : '';

Basically, I want to check if the variable is set, and if not, then return a default value.

https://stackoverflow.com/a/18603279/165330 :

before php 7 : no

$address = isset($node->field_naam_adres['und'][0]['value']) ? $node->field_naam_adres['und'][0]['value'] : '';

from php 7 : yes

$address = $node->field_naam_adres['und'][0]['value'] ?? 'default';

If you can get away with relying on truthiness and falsiness instead of the more direct isset , you can leave out the middle statement in a ternary like this:

$address = $node->field_naam_adres['und'][0]['value'] ?: '';

This works such that if the return value of the first statement evaluates as truthy, that value will be returned, otherwise the fallback will be used. You can see what various values will evaluate to as booleans here

It's important to note that if you use this pattern, you cannot wrap your initial statement in isset , empty , or any similar function. If you do, the return value from that statement simply becomes a boolean value. So while the above code will return either the value of $node->field_naam_adres['und'][0]['value'] or an empty string, the following code:

$address = isset($node->field_naam_adres['und'][0]['value']) ?: '';

Will return either TRUE or an empty string.

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