3v4l.org

run code in 300+ PHP versions simultaneously
<?php class CategoryTree { public $tree; private $failure = false; public function __construct() { // First element of the array represents the name of the category, so to iterate children, we have to go from index 1 $tree = $this->tree; $tree["root"] = array(); } private function &getCategoryWithNameInSubtree($name, &$subTreeRoot) { if (count($subTreeRoot) == 0) return $this->failure; // There are no branches coming from this root // So, the subtree has some branches to traverse... foreach ($subTreeRoot as $branchName => &$branch) { if ($branchName == $name) { // Search is over - this branch has the specified name return $branch; } else { $subTreeSearchResult = $this->getCategoryWithNameInSubtree($name, $branch); if($subTreeSearchResult) { return $subTreeSearchResult; } else { //If we have reached this, it means the name was not found in that branch } } } //We traversed all branches and no name was equal to the specified name return $this->failure; } public function &getCategoryWithName($name) { $tree = &$this->tree; return $this->getCategoryWithNameInSubtree($name, $tree); } } $c = new CategoryTree(); $c->tree=array("prima" => array("prima-prima" => [], "prima-seconda" => [], "prima-terza" => []), "seconda" => array("seconda-prima" => [], "seconda-seconda" => [], "seconda-terza" => []), "terza" => array("terza-prima" => [], "terza-seconda" => [], "terza-terza" => []), ); $seconda = $c->getCategoryWithName("seconda"); $seconda[] = "added"; print "cat is: <pre>"; print_r($seconda); print "</pre>"; print "ct is: <pre>"; print_r($c); print "</pre>";

preferences:
59.16 ms | 402 KiB | 5 Q