EDIT
I know I’m a new poster here, but I’m not new to StackOverflow. I’ve never seen people make up completely new solutions to problems as I’m seeing below. I provided the input, the output, and the expected output. The accepted answer will work within these guidelines.
I have am trying to write an array writing function that works as described below
// existing array
$config = array("preserve" => "please");
function set($key, $value){
global $config;
if(count($keys = explode(':', $key)) > 1){
$key = array_shift($keys);
while($k = array_pop($keys)){
$value = array($k => $value);
}
}
return $config[$key] = $value;
}
// set
set("foo", "bar");
set("pokemon:trainer", "ashk");
set("pokemon:favorite", "diglett"); // overwrites pokemon:trainer :(
print_r($config);
Output
Array
(
[preserve] => please
[foo] => bar
[pokemon] => Array
(
[favorite] => diglett
)
)
Oh no! Who’s the pokemon trainer? Ash Ketchum has been forgotten!
I understand why it’s breaking, but I can’t find out how I should write this function. I sense the need for recursion, but I’m not sure how to implement it :\
Output should be
Array
(
[preserve] => please
[foo] => bar
[pokemon] => Array
(
[trainer] => ashk
[favorite] => diglett
)
)
Now that I have over 100 rep, I can finally post this as a real answer and mark it as accepted.
This is quite a neat little snippet 🙂