1

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.

LittleBobbyTables - Au Revoir
  • 32,008
  • 25
  • 109
  • 114
mgoubert
  • 313
  • 1
  • 5
  • 16

2 Answers2

3

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

Community
  • 1
  • 1
imme
  • 598
  • 1
  • 9
  • 22
  • One could use the "dirty" way and suppress all warnings/notices by using this `@$node->field_naam_adres['und'][0]['value'] ?: '';` in php < 7 – OderWat Sep 13 '17 at 12:06
0

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.

Ben
  • 316
  • 1
  • 7
  • But `isset()` avoids the notice when you try to read a not-set value. That's why you use isset. So this does something else. The actual answer is: you can't get it shorter. – Nanne Mar 05 '15 at 20:14