0

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?

Matt
  • 896
  • 5
  • 18
  • 47
  • 2
    You don't need to test each level separately. One `isset()` will test all the levels. You can also use the `??` shortcut, see https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op – Barmar Jun 07 '22 at 20:51
  • Perhaps just something [like this](https://3v4l.org/k6mB9) ? – Jaquarh Jun 07 '22 at 20:54

1 Answers1

1

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;
IMSoP
  • 89,526
  • 13
  • 117
  • 169
  • // Using short-hand ternary is WRONG. $var = true or false; isset($this->getValue()[0]['value']) = boolean TRUE – YanAlex Feb 28 '23 at 12:04
  • 1
    @YanAlex Oh, I see what you mean; it will end up forcing a `true`, rather than taking the returned value. I've removed that example, thanks. – IMSoP Feb 28 '23 at 12:27