3v4l.org

run code in 300+ PHP versions simultaneously
<?php $array = [ "# Grandparent #1", "# Grandparent #2", "## Parent #2-1", "### Child #2-1-1", "## Parent #2-2", "### Child #2-2-1", "### Child #2-2-2", "## Parent #2-3", "## Parent #2-4", "# Grandparent #3", "## Parent #3-1", ]; function recurse(array $lines, int $level = 1): array { $tree = []; $directDescendants = []; foreach($lines as $line) { [$hashes, $name] = explode(' ', $line, 2); $depth = strlen($hashes); if ($depth === $level) { if ($directDescendants) { $parent['children'] = recurse($directDescendants, $level + 1); } $directDescendants = []; // reset collection of direct descendants unset($parent); // destroy reference $parent = ['name' => $name]; // name the member $tree[] = &$parent; // push the reference variable into the tree } elseif ($depth > $level) { $directDescendants[] = $line; // collect only direct descendants of current level parent member } } if ($directDescendants) { $parent['children'] = recurse($directDescendants, $level + 1); } return $tree; } var_export(recurse($array));
Output for git.master, git.master_jit, rfc.property-hooks
array ( 0 => array ( 'name' => 'Grandparent #1', ), 1 => array ( 'name' => 'Grandparent #2', 'children' => array ( 0 => array ( 'name' => 'Parent #2-1', 'children' => array ( 0 => array ( 'name' => 'Child #2-1-1', ), ), ), 1 => array ( 'name' => 'Parent #2-2', 'children' => array ( 0 => array ( 'name' => 'Child #2-2-1', ), 1 => array ( 'name' => 'Child #2-2-2', ), ), ), 2 => array ( 'name' => 'Parent #2-3', ), 3 => array ( 'name' => 'Parent #2-4', ), ), ), 2 => array ( 'name' => 'Grandparent #3', 'children' => array ( 0 => array ( 'name' => 'Parent #3-1', ), ), ), )

This tab shows result from various feature-branches currently under review by the php developers. Contact me to have additional branches featured.

Active branches

Archived branches

Once feature-branches are merged or declined, they are no longer available. Their functionality (when merged) can be viewed from the main output page


preferences:
33.51 ms | 408 KiB | 5 Q