2

A basic check if an array element exists:

$foo = isset($country_data['country']) ? $country_data['country'] : ''; 

That feels really verbose and I'm now asking is there a shorter way to do that?

I could suppress the error with @:

$foo = @$country_data['country'] 

But that seems wrong somehow...

I know that with variables you can do something like this:

$foo = $bar ?: ''; 

But that doesn't work with isset().

0

1 Answer 1

4

In PHP7 you can use null coalescing operator ??.

It'll take the first non-null value in a chain.

You could do this:

$foo = $country_data['country'] ?? ''; 

It's the same thing as doing

$foo = isset($country_data['country']) ? $country_data['country'] : ''; 

And also, you can chain even further.

For example, you can try with many array indexes:

$foo = $country_data['country'] ?? $country_data['state'] ?? $country_data['city'] ?? ''; 

If every item is null (!isset()), it will take the empty string at the end, but if any of them exists, the chain will stop there.

If you don't have PHP7 (which you should), you can use this function that I found in this answer:

function coalesce() { $args = func_get_args(); foreach ($args as $arg) { if (!empty($arg)) { return $arg; } } return NULL; } $foo = coalesce($country_data['country'], ''); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.