3v4l.org

run code in 500+ PHP versions simultaneously
<?php $comments = [ [1, 1, 'Comment 1'], [2, 1, 'Comment 2'], [3, 2, 'Comment 3'], [4, 1, 'Comment 4'], [5, 2, 'Comment 5'], [6, 3, 'Comment 6'], [7, 7, 'Comment 7'], ]; $map = []; foreach($comments as $c) { $id = $c[0] === $c[1] ? 0 : $c[1]; $map[$id][] = $c; } function print_comments($arr, $depth) { global $map; foreach($arr as $c) { echo str_repeat("--", $depth) . "{$c[2]}\n"; print_comments($map[$c[0]] ?? [], $depth+1); } } print_comments($map[0], 0);
Output for 8.0.1 - 8.0.30, 8.1.0 - 8.1.34, 8.2.0 - 8.2.31, 8.3.0 - 8.3.31, 8.4.1 - 8.4.22, 8.5.0 - 8.5.7
Comment 1 --Comment 2 ----Comment 3 ------Comment 6 ----Comment 5 --Comment 4 Comment 7

preferences:
83.64 ms | 1140 KiB | 4 Q