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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With