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
Release: 2024-12-11 09:48:10
Original
425 people have browsed it

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

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!

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