3v4l.org

run code in 300+ PHP versions simultaneously
<?php class A { private $query; public function &findNode(array $path) { $link = &$this->query; foreach ($path as $element) { $link = &$link[$element]; } return $link; } public function setValues(array $path, array $values) { $node = &$this->findNode($path); $node = array_merge($node ?? [], $values); unset($node); return $this; } public function setValueByPath(array $path, $value): self { $link = &$this->findNode($path); if (is_array($value)) { $link[] = $value; } else { $link = $value; } unset($link); return $this; } public function print() { print_r($this->query); } } $a = new A; $a ->setValues(['c', 'd'], [['test' => 1], ['test' => 2]]) ->setValues(['c', 'd'], [['test' => 3], ['test' => 4]]); $a ->setValueByPath(['a', 'b', 'c', 'd'], ['match' => 100500]) ->setValueByPath(['a', 'b', 'c', 'd'], ['match' => 1000]) ->setValueByPath(['a', 'b', 'c', 'd', 1, 'zzz'], 'lol'); $a->print();

preferences:
52.15 ms | 402 KiB | 5 Q