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

How to Dynamically Set Nested Array Data Using a String Path in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-11 09:48:10480browse

How to Dynamically Set Nested Array Data Using a String Path in PHP?

Using a String Path to Set Nested Array Data

Question:
How can I dynamically set nested array data using a string path, such as "cars.honda.civic" to $data'cars'['civic'] without relying on eval()?

Answer:
The reference operator (&) allows for this dynamic setting:

$temp = &$data;
foreach ($exploded_path as $key) {
    $temp = &$temp[$key];
}
$temp = $value;
unset($temp);

By using this approach, you can efficiently set the nested array data without the need for eval(). Here's how it works:

  • $temp is initialized as a reference to the root array ($data).
  • The loop iterates over the exploded path, updating $temp to successively reference the existing arrays.
  • $temp is finally assigned the desired value $value.
  • unset($temp) clears the reference, preventing unintentional side effects.

The above is the detailed content of How to Dynamically Set Nested Array Data 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