Example 1 — Listing a Folder with scandir()
We create a demo folder with three files and list it. First we print the raw result, then a cleaned version.
<?php
$folder = __DIR__ . '/demo-scandir';
mkdir($folder);
foreach (['b.txt', 'c.txt', 'a.txt'] as $name) {
file_put_contents($folder . '/' . $name, 'x');
}
$all = scandir($folder);
echo "All: ", implode(', ', $all), PHP_EOL;
$files = array_values(array_diff($all, ['.', '..']));
echo "Files: ", implode(', ', $files), PHP_EOL;
echo "Count: ", count($files), PHP_EOL;
foreach ($files as $name) {
unlink($folder . '/' . $name);
}
rmdir($folder); How It Works
- The files are created in a mixed order (b, c, a) to show that scandir() sorts them.
- The raw result starts with '. ' and '..', followed by the names in alphabetical order.
- array_diff() removes the two special entries, and array_values() renumbers the keys.
- count() now gives the number of real files, which is 3.

