How can the PHP function "pathinfo()" be utilized to determine the file extension of a given file, and how can this information be used to selectively delete files based on their extension?

To determine the file extension of a given file using the PHP function "pathinfo()", you can extract the extension by accessing the 'extension' key in the array returned by the function. To selectively delete files based on their extension, you can compare the extracted extension with the desired extension(s) and delete the file if it matches.

$directory = '/path/to/directory/';

$files = scandir($directory);

foreach($files as $file) {
    if($file != '.' && $file != '..') {
        $fileInfo = pathinfo($directory . $file);
        $fileExtension = $fileInfo['extension'];

        if($fileExtension == 'txt') { // Change 'txt' to the desired file extension
            unlink($directory . $file);
            echo "Deleted file: " . $file . "\n";
        }
    }
}