What is the difference between using a while loop and a foreach loop in PHP when reading files from a directory?

When reading files from a directory in PHP, using a while loop involves opening the directory handle, iterating over each file using readdir() function, and closing the handle when done. On the other hand, using a foreach loop with glob() function simplifies the process by directly getting an array of file paths in the directory.

// Using a while loop to read files from a directory
$dir = "/path/to/directory/";
if ($handle = opendir($dir)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            echo "File: $file\n";
        }
    }
    closedir($handle);
}

// Using a foreach loop with glob() to read files from a directory
$files = glob("/path/to/directory/*");
foreach ($files as $file) {
    echo "File: $file\n";
}