Assume I have the following function
function setArray(&$array, $key, $value)
{
$array[$key] = $value;
}
In the above function, key is only at the first level, what if I want to set the key at the 2nd or 3rd levels, how to rewrite the function?
e.g.
$array['foo']['bar'] = 'test';
I want to use the same function to set the array value
This one should work. Using this function you can set any array element in any depth by passing a single string containing the keys separated by .
function setArray(&$array, $keys, $value) {
$keys = explode(".", $keys);
$current = &$array;
foreach($keys as $key) {
$current = &$current[$key];
}
$current = $value;
}
You can use this as follows:
$array = Array();
setArray($array, "key", Array('value' => 2));
setArray($array, "key.test.value", 3);
print_r($array);
output:
Array (
[key] => Array
(
[value] => 2
[test] => Array
(
[value] => 3
)
)
)
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