This is little example of using generators with recursion. Used version of php is 5.5.5[php]<?phpdefine ("DS", DIRECTORY_SEPARATOR);define ("ZERO_DEPTH", 0);define ("DEPTHLESS", -1);define ("OPEN_SUCCESS", True);define ("END_OF_LIST", False);define ("CURRENT_DIR", ".");define ("PARENT_DIR", "..");function DirTreeTraversal($DirName, $MaxDepth = DEPTHLESS, $CurrDepth = ZERO_DEPTH){ if (($MaxDepth === DEPTHLESS) || ($CurrDepth < $MaxDepth)) { $DirHandle = opendir($DirName); if ($DirHandle !== OPEN_SUCCESS) { try{ while (($FileName = readdir($DirHandle)) !== END_OF_LIST) { if (($FileName != CURRENT_DIR) && ($FileName != PARENT_DIR)) { $FullName = $DirName.$FileName; yield $FullName; if(is_dir($FullName)) { $SubTrav = DirTreeTraversal($FullName.DS, $MaxDepth, ($CurrDepth + 1)); foreach($SubTrav as $SubItem) yield $SubItem; } } } } finally { closedir($DirHandle); } } }}$PathTrav = DirTreeTraversal("C:".DS, 2);print "<pre>";foreach($PathTrav as $FileName) printf("%s\n", $FileName);print "</pre>";[/php]