3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?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>";
based on YOspH
Output for 5.6.0 - 5.6.30, hhvm-3.15.4, 7.0.0 - 7.3.0alpha1
cat is: <pre>Array ( [seconda-prima] => Array ( ) [seconda-seconda] => Array ( ) [seconda-terza] => Array ( ) [0] => added ) </pre>ct is: <pre>CategoryTree Object ( [tree] => Array ( [prima] => Array ( [prima-prima] => Array ( ) [prima-seconda] => Array ( ) [prima-terza] => Array ( ) ) [seconda] => Array ( [seconda-prima] => Array ( ) [seconda-seconda] => Array ( ) [seconda-terza] => Array ( ) ) [terza] => Array ( [terza-prima] => Array ( ) [terza-seconda] => Array ( ) [terza-terza] => Array ( ) ) ) [failure:CategoryTree:private] => ) </pre>