Passing Nested Keys to Custom Array Lookup Function, PHP
I have a custom array lookup function which I pass both array and key to and it returns the value if it finds it or an empty string. It has been working well as intended only to realize that I cannot pass a nested key to it. By nesting I mean key like [outer-key][inner-key]. The function (in a class) is:
public function getArrayValueSafely($dataArray, $dKey){
if(!is_array($dataArray) || count($dataArray) < 1){
return false;
}
if(strlen($dKey) < 1){
return false;
}
$retVal = '';
try {
$retVal = $dataArray[$dKey];
} catch (Exception $e) {
//echo 'Caught exception: ', $e->getMessage(), "\n";
}
return $retVal;
}
The warning is always:
Warning: Undefined array key "['SUBJECT_STRANDS']['RELIGION']"
Whether the keys is given as: ['SUBJECT_STRANDS']['RELIGION']
or [SUBJECT_STRANDS][RELIGION]
; the keys are definitely existing.
Any pointers to solve this will be highly appreciated as I am currently forced to pull the data using outer-key, then do a second lookup using inner-key.
Sample call as requested by @chris-haas:
$currentKey = "['SUBJECT_STRANDS']['RELIGION']";
//$currentKey = "[SUBJECT_STRANDS][RELIGION]"; //tried this also
$currentStrands = $this->getArrayValueSafely($lastExamData, $currentKey);
Solution 1:
You could maintain a reference of the current array, while iterating over the keys you want to traverse.
function getArrayValueSafely($dataArray, $keys)
{
$ref = &$dataArray; // Start with the given array
foreach ($keys as $key) { // loop over the keys
if (! isset($ref[$key])) { // key not found, return.
return false;
}
$ref = $ref[$key]; // move the pointer on sub array.
}
return $ref; // return reference value.
}
// Sample Data :
$lastExamData = ['SUBJECT_STRANDS' => ['RELIGION' => 'data']];
// Keys to traverse :
$currentKey = ['SUBJECT_STRANDS', 'RELIGION'];
// Get the value
$currentStrands = getArrayValueSafely($lastExamData, $currentKey);
var_dump($currentStrands); // string(4) "data"
live demo