Skip to content
Advertisement

Method to change specific value inside multidimensional array

Given a class with a multidimensional array as private property.

I’m trying to write a method setValue() which could change any value of this private array by passing:

  • some kind of path to a specific value (e.g. $path = [‘lorem’ => [‘ipsum’ => [‘dolor’ => [‘sit’ => null]]]];)
  • the new value

JavaScript

Thanks to a comment of Gabriel on php.net I was able to find a working solution.

You can see my solution among the answers below.

What I actualy want to know: What are alternative approaches?

Advertisement

Answer

There are some recursive array built-in functions that may help you here:

JavaScript

Output:

JavaScript

However looking at your original question targeting the array is likely an easier syntax, especially if you are only changing one attribute at a time. You’d have to change the visibility of the array accordingly:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement