PHP DirectoryIterator
Enumerate immediate directory entries and filter their names by suffix.
A simple example
DirectoryIterator
- Start with One folder containing a.txt and b.txt
- Do this List and sort its names
- Result a.txt, b.txt
Syntax
new DirectoryIterator($base)
Run these examples in PHP
Save one example at a time as lesson.php. Use PHP 8.2 or later.
php lesson.phpCount only the invoices in a folder
A market stall saves two CSV invoices and a text note in the same folder. Count just the CSV entries for the daily summary without depending on the order returned by the filesystem.
<?php
$base = sys_get_temp_dir() . DIRECTORY_SEPARATOR . bin2hex(random_bytes(12));
if (!mkdir($base, 0700)) throw new RuntimeException("Cannot create workspace");
try {
foreach (['a.csv', 'b.csv', 'note'] as $name) {
if (!touch($base . '/' . $name)) throw new RuntimeException('Cannot create entry');
}
$count = 0;
foreach (new DirectoryIterator($base) as $entry) {
if ($entry->isFile() && $entry->getExtension() === 'csv') $count++;
}
echo $count, PHP_EOL;
} finally {
foreach (['a.csv', 'b.csv', 'note'] as $name) {
$path = $base . '/' . $name;
if (is_link($path) || is_file($path)) unlink($path);
elseif (is_dir($path)) rmdir($path);
}
rmdir($base);
}
2
The two CSV names pass the filter and the text note is excluded.
Inventory class submissions
A teacher receives two top-level files and one file in a team folder. Count regular files in the top-level folder only. Do not count subfolders as files.
Inventory rehearsal parts
A school stores one score and two parts in a subfolder. Count regular files in the top-level folder only. Do not count subfolders as files.
What to watch for
Directory enumeration order is unspecified. Sort first if the order matters.