0

I have this isset() below because I want to show an empty string if the result of $this->field($content, 'description') is null.

However doing like this it shows

Cannot use isset() on the result of an expression

Do you know how to properly achieve this?

return [
    'description' => isset($this->field($content, 'description') ? $this->field($content, 'description') : '',
    //...
];
Will B.
  • 17,883
  • 4
  • 67
  • 69
Ozzdev
  • 65
  • 1
  • 11
  • 1
    Save the expressions result to a variable and pass that to `isset()`. See the 'warning' part on the docs page: https://www.php.net/manual/en/function.isset.php#refsect1-function.isset-notes – 0stone0 Feb 23 '22 at 11:49

2 Answers2

2

I'd use the null coalescing operator ?? (https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce)

return [
    'description' => $this->field($content, 'description') ?? '',
    //...
];
Will B.
  • 17,883
  • 4
  • 67
  • 69
Tom Regner
  • 6,856
  • 4
  • 32
  • 47
  • Like that it shows "Argument #1 ($content) must be of type array, null given, but it strange doing for example only like this works: " 'description' => '', ". Do you know what can be the issue? Thanks – Ozzdev Feb 23 '22 at 11:54
  • @Ozzdev *only like this works: `" 'description' => '', ".`*, we would need to see your code that is processing the return value of your code-snippet but that would be a separate question. If resolving one issue exposes another, it is not fair to those providing the initial resolution to keep raising the bar and altering the original question with a new issue. – Will B. Feb 23 '22 at 12:03
  • 1
    @WillB. nice catch, I added the ellipsis from the OP without thinking. – Tom Regner Feb 23 '22 at 12:11
1

You can use php ternary operator ?:

return [
    'description' => $this->field($content, 'description') ?: '',
    //...
];
Will B.
  • 17,883
  • 4
  • 67
  • 69
Anisur Rahman
  • 644
  • 1
  • 4
  • 17
  • 1
    Please keep in mind that this will match on all falsey values such as `0, false, "0", [], null`, as opposed to explicitly `null`. – Will B. Feb 23 '22 at 12:11