Skip to content
PHP Logo

How can the code snippet be improved by using glob() function in PHP?

The issue with the current code snippet is that it manually loops through all files in a directory to find files with a specific extension. This can be inefficient and error-prone. Using the glob() function in PHP simplifies this process by returning an array of files that match a specified pattern, such as all files with a specific extension.

php
// Improved code snippet using glob() function
$files = glob('/path/to/directory/*.txt');

foreach($files as $file) {
    echo $file . "<br>";
}