PHP: Look in to a multi-dimensional array using array_dive()
I have a multi-dimensional array that I need to extract data from. Given a string in the format of "person.first" I want to descend in to the array looking for person -> first. I wrote this array_dive()
function to facilitate this lookup.
function array_dive(string $needle, array $haystack) {
// Split at the periods
$parts = explode(".", $needle);
// Loop through each level of the hash looking for elem
$arr = $haystack;
foreach ($parts as $elem) {
//print "Diving for $elem<br />";
$arr = $arr[$elem] ?? null;
// If we don't find anything stop looking
if ($arr === null) {
break;
}
}
// If we find a scalar it's the end of the line, anything else is just
// another branch, so it doesn't cound as finding something
if (is_scalar($arr)) {
$ret = $arr;
} else {
$ret = null;
}
return $ret;
}
Here is a sample script that shows the function in action.