What are common pitfalls when using PHP functions like readdir and sort together?

When using PHP functions like readdir and sort together, a common pitfall is that the sort function may not work correctly on the array returned by readdir because it may contain extra elements like '.' and '..'. To solve this issue, you can use array_diff to remove these extra elements before sorting the array.

$dir = './path/to/directory';
$files = array_diff(scandir($dir), array('..', '.')); // Remove '.' and '..' from the array
sort($files); // Sort the remaining elements
foreach ($files as $file) {
    echo $file . "\n";
}