I've just coded a little function to check and get a deep array value. Basically, I need to return the value or null if it's not set or does not exists, or in general not useful for databases records. I need to check things like $myarray[key1][key2][key3] etc..
function get_array_deep_value(array $array, array $fields){
$value = $array;
foreach($fields as $field){
$v = $value[$field] ?? null;
if(empty($v) && $v != 0){ // note: using != operator because it will convert '0' to 0 (while !== does not)
$value = null;
break;
}
$value = $v;
}
return $value;
}
Any possible improvements? :)
empty()that should happen before null coalescing. \$\endgroup\$breakseems like it is part of a protective measure. Would you prefer instead tothrowan exception because the path to the desired element suffered a breakage? How do you differentiate between a truly foundnulland a fallbacknull? \$\endgroup\$