Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check if set of nested array keys exist all at once

Tags:

php

To avoid invalid array key errors I'm checking if every array key exists that I'm checking. When I'm checking whether a key is set on something nested 2 or 3 levels deep I'm resorting to this

$var = isset($this->getValue()[0]) && isset($this->getValue()[0]['value']) ? $this->getValue()[0]['value'] : false;

It works but it looks pretty clunky to me and doesn't feel right.

I've looked at posts like this What's quicker and better to determine if an array key exists in PHP? but they don't seem to apply to situations where I need to check multiple levels.

Is there a more proper way to do this?

like image 807
Matt Avatar asked Oct 18 '25 02:10

Matt


1 Answers

Both isset and the null coalescing operator will short-cut as soon as they see an unset dimension, so can safely be used to test deep arrays like this.

So the following will all give the same result (assuming getValue() has no side-effects):

// Your example
$var = isset($this->getValue()[0]) && isset($this->getValue()[0]['value']) ? $this->getValue()[0]['value'] : false;

// Reduced to a single isset
$var = isset($this->getValue()[0]['value']) ? $this->getValue()[0]['value'] : false;

// Using null coalesce
$var = $this->getValue()[0]['value'] ?? false;
like image 188
IMSoP Avatar answered Oct 20 '25 17:10

IMSoP