fork download
  1. <?php
  2. function set_config($key, $value, $config = array()){
  3. // The base case of the recursion is that no keys are left to recurse through
  4. // so we return the value
  5. if($key == ''){
  6. return $value;
  7. } else {
  8. // break the key into an array and set the current one to the first item
  9. $keys = explode('/', $key);
  10. $current_key = array_shift($keys);
  11.  
  12. // check if the key already exists in the array and if so just update it's contents
  13. // by merging existing items with the new one
  14. if(isset($config[$current_key]))
  15. $config[$current_key] = array_merge($config[$current_key], set_config(join('/',$keys), $value, $config[$current_key]));
  16.  
  17. // no keys means we are at the base of the recursion, return just the value
  18. else
  19. return array($current_key => set_config(join('/',$keys), $value));
  20. }
  21.  
  22. return $config;
  23. // done
  24. }
  25.  
  26. $config = array();
  27. $config = set_config('db/yum/user','val', $config);
  28. print_r($config);
  29. $config = set_config('db/yum/server','val2', $config);
  30. print_r($config);
  31. $config = set_config('db/yum/a/few/more/levels/for/fun','LOLOLOLOL', $config);
  32. print_r($config);
  33.  
  34. ?>
Success #stdin #stdout 0.02s 13064KB
stdin
Standard input is empty
stdout
Array
(
    [db] => Array
        (
            [yum] => Array
                (
                    [user] => val
                )

        )

)
Array
(
    [db] => Array
        (
            [yum] => Array
                (
                    [user] => val
                    [server] => val2
                )

        )

)
Array
(
    [db] => Array
        (
            [yum] => Array
                (
                    [user] => val
                    [server] => val2
                    [a] => Array
                        (
                            [few] => Array
                                (
                                    [more] => Array
                                        (
                                            [levels] => Array
                                                (
                                                    [for] => Array
                                                        (
                                                            [fun] => LOLOLOLOL
                                                        )

                                                )

                                        )

                                )

                        )

                )

        )

)