Skip to content

Instantly share code, notes, and snippets.

@aklump
Last active August 29, 2015 14:16
Show Gist options
  • Save aklump/1affd8f672d9ea639489 to your computer and use it in GitHub Desktop.
Save aklump/1affd8f672d9ea639489 to your computer and use it in GitHub Desktop.
Set a multidimensional array element based on an array of nested keys.
/**
* 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 <sourcecode@intheloftstudios.com>
*/
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