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?

1
  • 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 Commented Jun 22, 2018 at 12:01

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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 : I have cross checked or works for laravel not in <?php ... ?> tag, at my end.
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.
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".
Oh sorry, I think I should mention it in my answer
|
1

Since PHP 7 you can do

$country['capital'] ?? null; 

1 Comment

PHP 7.0 actually

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.