How can the `scandir()` function be used to list files in a directory and what are the best practices for handling the output?

The `scandir()` function in PHP can be used to list files in a directory by returning an array of file names. To handle the output, it is best to check for errors, filter out unwanted files (such as `.` and `..`), and iterate over the array to process each file individually.

$directory = "/path/to/directory";

if (is_dir($directory)) {
    $files = scandir($directory);
    
    foreach ($files as $file) {
        if ($file != "." && $file != "..") {
            // Process each file here
            echo $file . PHP_EOL;
        }
    }
} else {
    echo "Invalid directory";
}