Skip to content

Instantly share code, notes, and snippets.

@sam-ngu
sam-ngu / iterate.php
Last active June 24, 2021 11:54
PHP iterator to recursively iterate through a folder.
<?php
$folderPath = __DIR__ . '/path/to/folder/';
try {
$dirIterator = new \RecursiveDirectoryIterator($folderPath);
/** @var \RecursiveDirectoryIterator | \RecursiveIteratorIterator $it */
$it = new \RecursiveIteratorIterator($dirIterator);
// the valid() method checks if current position is valid eg there is a valid file or directory at the current position