Using a string path to set nested array data
I have an unusual use-case I'm trying to code for. The goal is this: I want the customer to be able to provide a string, such as:
"cars.honda.civic = On"
Using this string, my code will set a value as follows:
$data['cars']['honda']['civic'] = 'On';
It's easy enough to tokenize the customer input as such:
$token = explode("=",$input);
$value = trim($token[1]);
$path = trim($token[0]);
$exploded_path = explode(".",$path);
But now, how do I use $exploded path to set the array without doing something nasty like an eval?
Use the reference operator to get the successive existing arrays:
$temp = &$data;
foreach($exploded as $key) {
$temp = &$temp[$key];
}
$temp = $value;
unset($temp);
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;
}