3v4l.org

run code in 300+ PHP versions simultaneously
<?php function getComments(int $parentId = null): array { $comments = [ ['id' => 1, 'parentId' => null, 'comment' => 'foo'], ['id' => 2, 'parentId' => null, 'comment' => 'bar'], ['id' => 3, 'parentId' => 1, 'comment' => 'foo 1'], ['id' => 4, 'parentId' => 1, 'comment' => 'foo 2'], ['id' => 5, 'parentId' => 4, 'comment' => 'foo 2-1'], ['id' => 6, 'parentId' => 2, 'comment' => 'foo bar'], ['id' => 7, 'parentId' => 5, 'comment' => 'foo 2-1-1'], ]; return array_filter($comments, fn (array $comment): bool => $comment['parentId'] === $parentId); } function showComments(?int $parentId = null, int $level = 0) { foreach (getComments($parentId) as $comment) { printf('%sComment id: %d - comment %s', str_repeat(' ', $level), $comment['id'], $comment['comment']); echo "\n"; showComments($comment['id'], $level + 1); } } showComments();

preferences:
25.12 ms | 406 KiB | 5 Q