0

I have this kind of test again, and again, and I feel like there is a more elegant way to do it.

(isset($country['capital'])) ? $country['capital'] : null

Can you help me?

Juliatzin
  • 18,455
  • 40
  • 166
  • 325
  • Your parentheses around the `isset()` are useless. Put the whole ternary operator between parentheses while nesting them or in string concatenation. But the null coalescing operator is the way to go if you have PHP7 – AymDev Jun 22 '18 at 12:01

2 Answers2

3

You can use or Operator In Laravel Blade template

$country['capital'] or null 

And In php 7 you can use Null coalescing operator

$country['capital'] ?? null

From PHP docs

The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109
  • That `or` won't do much. It's not Laravel, it's PHP (unless I'm really missing something about Laravel overloading PHP operators!?). – deceze Jun 22 '18 at 12:52
  • @deceze : I have cross checked `or` works for laravel not in `` tag, at my end. – Niklesh Raut Jun 22 '18 at 12:53
  • What exactly does "in Laravel" mean then? Laravel is still written in PHP. Are you referring to some templating system? Then reference to documentation please. – deceze Jun 22 '18 at 12:55
  • @deceze : I hope you aware about [this article](https://laravel-news.com/blade-or-operator) – Niklesh Raut Jun 22 '18 at 12:55
  • 1
    So you're referring specifically to *Blade template syntax.* That's just one specific subcomponent of Laravel and not generally applicable to all "Laravel code". – deceze Jun 22 '18 at 12:57
  • 1
    Oh sorry, I think I should mention it in my answer – Niklesh Raut Jun 22 '18 at 12:59
1

Since PHP 7 you can do

$country['capital'] ?? null;
DonCallisto
  • 29,419
  • 9
  • 72
  • 100