Home >Backend Development >PHP Tutorial >How to Safely Update Nested Array Data Using a String Path in PHP?
Accessing Nested Array Data with a String Path
Suppose you have a customer entering a string that follows a particular format, such as "cars.honda.civic = On". The objective is to utilize this string to update a nested array in the following manner:
$data['cars']['honda']['civic'] = 'On';
To begin, use the explode function to tokenize the input string:
$token = explode("=", $input); $value = trim($token[1]); $path = trim($token[0]); $exploded_path = explode(".", $path);
Now, to set the array elements without relying on unsafe methods like eval, use the reference operator (&). The & operator provides a reference to the variable, allowing you to modify its value directly.
$temp = &$data; foreach ($exploded_path as $key) { $temp = &$temp[$key]; } $temp = $value; unset($temp);
In essence, $temp acts as a pointer to the current level of the array. The loop iterates through the elements specified in the string path, progressively creating or retrieving the necessary arrays. Finally, the value is set, and unset($temp) removes the reference to the nested element.
The above is the detailed content of How to Safely Update Nested Array Data Using a String Path in PHP?. For more information, please follow other related articles on the PHP Chinese website!