'Attempt to retrieve nested key array value given unkown amount of supplied keys into PHP function
I would like to supply a function with an array of keys (unknown quantity) and a value to then set the corresponding nested array value (using those keys and value). I know how to do this for retrieval, just not for assigning. For retrieval, I do:
function test($keys, $value){
$arr = ["key1" => ["key2" => true], "key3" => true];
$nestedArrayValue = $arr;
foreach($keys as $key){
$nestedArrayValue = $arr[$key];
}
return $nestedArrayValue;
}
But when assigning a value, that $nestedArrayValue is a copy, so it won't actually change the $arr. Likewise, if I were to pass by reference where $nestedArrayValue = &$arr, the foreach would override the entire $arr each time. For example:
function test($keys, $value){
$arr = ["key1" => ["key2" => true], "key3" => true];
$nestedArrayValue = &$arr;
foreach($keys as $key){
$nestedArrayValue = $arr[$key];
}
$nestedArrayValue = $value;
var_dump($arr);
}
test(["key1", "key2"], "test value");
//OUTPUT:
string(10) "test value"
The entire $arr gets overridden (which it should). My question is: how do I assign directly to $arr given an unknown amount of keys (as an array)? Is it possible?
UPDATE:
Here's a pseudo code example of what I am trying to do:
// If this is supplied into function:
["key1","key2"]
// Then this is attempted to be returned:
$arr["key1"]["key2"];
I figured out how to do ^ that, but what I can't seem to figure out how to do this:
// If this is supplied for keys:
["key1","key2"]
// And if this is supplied as value:
"test value"
// Then it should attempt to set:
$arr["key1"]["key2"] = "test value"
Is that possible?
Solution 1:[1]
You set the $nestedArrayValue reference to the array and in the loop you actually replace the entire array with the value $arr[$key]. It was necessary to change the reference to the next key:
$nestedArrayValue = &$arr;
foreach($keys as $key){
// $nestedArrayValue = $arr[$key];
$nestedArrayValue = &$nestedArrayValue[$key];
}
$nestedArrayValue = $value;
And it would also be good to check the key for existence:
$nestedArrayValue = &$arr;
$found = true;
foreach($keys as $key){
if (array_key_exists($key, $nestedArrayValue)) {
$nestedArrayValue = &$nestedArrayValue[$key];
} else {
$found = false;
break;
}
}
if ($found) {
$nestedArrayValue = $value;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | id'7238 |
