Rastur
Rastur

Reputation: 137

Checking if an array key exists

I have a multidimensional array produced by json_decode(). The json is dynamically generated, that means some keys will be present randomly.

I would like to avoid Undefined index: notice, so i encapsulated the calls to the array in a function like this:

function exists($value) {
    if (isset($value)) {
        return $value;
    }
}

I then call data:

$something = exists($json_array['foo']['bar']['baz']);

But i still get the Undefined index: baz notice. Any suggestions?

Upvotes: 0

Views: 173

Answers (3)

Levi Morrison
Levi Morrison

Reputation: 19552

It seems you are new to PHP, so I'll give a bit lengthier answer than normal.

$something = exists($json_array['foo']['bar']['baz']);

This is equivalent to what you wrote:

$baz = $json_array['foo']['bar']['baz'];
$something = exists($baz);

As you may have noticed, this means that $json_array['foo']['bar']['baz'] is evaluated before it's passed to exists(). This is where the undefined index is coming from.

The correct idiom would be more like this:

$something = NULL;
if (isset($json_array['foo']['bar']['baz'])) {
    $something = $json_array['foo']['bar']['baz'];
}

The following is also identical to the above lines:

$something = isset($json_array['foo']['bar']['baz'])
    ? $json_array['foo']['bar']['baz']
    : NULL;

Upvotes: 2

StackSlave
StackSlave

Reputation: 10627

$json_array['foo']['bar']['baz'] fails when you pass it as an argument, before it's passed to isset(). That is your problem.

Upvotes: 0

David d C e Freitas
David d C e Freitas

Reputation: 7511

You would have to chain the exists calls one by one, because you are trying to dereference the array before you send it to the exists function.

See this question for more info: Check if a "run-time" multidimensional array key exists

Upvotes: 1

Related Questions