Home >Backend Development >PHP Tutorial >How to Safely Set Nested Array Values Using a String Path in PHP?
Setting Nested Array Data Using a String Path
In this use case, a string input aims to set a nested array value. For instance:
"cars.honda.civic = On"
This string should result in:
$data'cars'['civic'] = 'On';
While tokenizing the input is straightforward:
$token = explode("=",$input);
$value = trim($token[1]);
$path = trim($token[0]);
$exploded_path = explode(".",$path);
The challenge lies in setting the array without resorting to risky techniques like eval.
Solution
A solution involves utilizing the reference operator (&) to obtain successive existing arrays:
$temp = & $data;
foreach($exploded as $key) {
$temp = & $temp[$key];
}
$temp = $value;
unset($temp);
This method allows you to navigate through nested arrays without hard-coding each level.
The above is the detailed content of How to Safely Set Nested Array Values Using a String Path in PHP?. For more information, please follow other related articles on the PHP Chinese website!