Last active
August 29, 2015 14:16
-
-
Save aklump/1affd8f672d9ea639489 to your computer and use it in GitHub Desktop.
Set a multidimensional array element based on an array of nested keys.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Set a multidimensional array element based on an array of nested keys. | |
* | |
* @code | |
* $vars = array(); | |
* $string = 'some.string.of.keys'; | |
* $keys = explode('.', $string); | |
* $value = 'final value'; | |
* array_set_nested_element($vars, $keys, $value); | |
* @endcode | |
* | |
* The end result is $vars['some']['string']['of']['keys'] = 'final value'; | |
* | |
* @param array &$array The base array. | |
* @param array &$keys An array of keys, each successive a child of the former. | |
* @param mixed $value The final value to set on the last child key. | |
* | |
* @author Aaron Klump <[email protected]> | |
*/ | |
function array_set_nested_element(&$array, &$keys, $value) { | |
if (!($key = array_shift($keys))) { | |
$array = $value; | |
return; | |
} | |
if (!isset($array[$key])) { | |
$array[$key] = array(); | |
} | |
$self = __FUNCTION__; | |
return $self($array[$key], $keys, $value); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment