What are the best practices for organizing folder search functions in PHP?

When organizing folder search functions in PHP, it is important to follow best practices to ensure efficiency and maintainability. One common approach is to create a separate function that recursively searches through directories for a specific file or pattern. This function should be well-documented and modular, allowing for easy reuse and modification.

function searchFiles($dir, $pattern){
    $files = [];
    
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
    
    foreach($iterator as $file){
        if(preg_match($pattern, $file)){
            $files[] = $file->getPathname();
        }
    }
    
    return $files;
}

// Example usage
$dir = '/path/to/directory';
$pattern = '/\.txt$/'; // Search for files ending in .txt
$results = searchFiles($dir, $pattern);

print_r($results);