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

How to Safely Set Nested Array Values Using a String Path in PHP?

DDD
DDDOriginal
2024-12-15 06:40:11768browse

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!

Statement:
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