Home > Backend Development > PHP Tutorial > How to Safely Update Nested Array Data Using a String Path in PHP?

How to Safely Update Nested Array Data Using a String Path in PHP?

Barbara Streisand
Release: 2024-12-18 02:59:10
Original
448 people have browsed it

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';
Copy after login

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);
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template