<?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();
- Output for 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.4, 8.3.6
- Comment id: 1 - comment foo
Comment id: 3 - comment foo 1
Comment id: 4 - comment foo 2
Comment id: 5 - comment foo 2-1
Comment id: 7 - comment foo 2-1-1
Comment id: 2 - comment bar
Comment id: 6 - comment foo bar
- Output for 8.3.5
- Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
Comment id: 1 - comment foo
Comment id: 3 - comment foo 1
Comment id: 4 - comment foo 2
Comment id: 5 - comment foo 2-1
Comment id: 7 - comment foo 2-1-1
Comment id: 2 - comment bar
Comment id: 6 - comment foo bar
- Output for 7.3.0 - 7.3.33
- Parse error: syntax error, unexpected '$comment' (T_VARIABLE), expecting '(' in /in/KPH2h on line 14
Process exited with code 255.
preferences:
139.36 ms | 401 KiB | 154 Q