any_h
any_h

Reputation: 578

A short method of checking if array value exists in PHP

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().

Upvotes: 2

Views: 498

Answers (1)

Phiter
Phiter

Reputation: 14982

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'], '');

Upvotes: 4

Related Questions