Using a string path to set nested array data
Well tested and 100% working code. Set, get, unset values from an array using "parents". The parents can be either array('path', 'to', 'value')
or a string path.to.value
. Based on Drupal's code
/**
* @param array $array
* @param array|string $parents
* @param string $glue
* @return mixed
*/
function array_get_value(array &$array, $parents, $glue = '.')
{
if (!is_array($parents)) {
$parents = explode($glue, $parents);
}
$ref = &$array;
foreach ((array) $parents as $parent) {
if (is_array($ref) && array_key_exists($parent, $ref)) {
$ref = &$ref[$parent];
} else {
return null;
}
}
return $ref;
}
/**
* @param array $array
* @param array|string $parents
* @param mixed $value
* @param string $glue
*/
function array_set_value(array &$array, $parents, $value, $glue = '.')
{
if (!is_array($parents)) {
$parents = explode($glue, (string) $parents);
}
$ref = &$array;
foreach ($parents as $parent) {
if (isset($ref) && !is_array($ref)) {
$ref = array();
}
$ref = &$ref[$parent];
}
$ref = $value;
}
/**
* @param array $array
* @param array|string $parents
* @param string $glue
*/
function array_unset_value(&$array, $parents, $glue = '.')
{
if (!is_array($parents)) {
$parents = explode($glue, $parents);
}
$key = array_shift($parents);
if (empty($parents)) {
unset($array[$key]);
} else {
array_unset_value($array[$key], $parents);
}
}
Based on alexisdm's response :
/**
* Sets a value in a nested array based on path
* See https://stackoverflow.com/a/9628276/419887
*
* @param array $array The array to modify
* @param string $path The path in the array
* @param mixed $value The value to set
* @param string $delimiter The separator for the path
* @return The previous value
*/
function set_nested_array_value(&$array, $path, &$value, $delimiter = '/') {
$pathParts = explode($delimiter, $path);
$current = &$array;
foreach($pathParts as $key) {
$current = &$current[$key];
}
$backup = $current;
$current = $value;
return $backup;
}
Use the reference operator to get the successive existing arrays:
$temp = &$data;
foreach($exploded as $key) {
$temp = &$temp[$key];
}
$temp = $value;
unset($temp);