skip to Main Content

I would like to test if the function array_map(‘unlink’, glob(‘…*.txt’)) did not encounter an error:
ex.:

try { 
  array_map('unlink', glob('/folder/my_files--*.txt'));
} 
catch (Exception $e) {
  echo 'Caught exception: ',  $e->getMessage(), "n";
}

In your opinion, does this code seem valid?
Thank you for your feedback !

2

Answers


  1. Chosen as BEST ANSWER

    Mmm!, in fact I'm too stupid, it doesn't matter the extension of the file, what I want is to empty the folder... Deceze's answer is very good if we want to specifically delete a type of file, among others other file types. I'm going to use DirectoryIterator:

    $iterator = new DirectoryIterator(dirname(__FILE__));
    foreach ($iterator as $fileinfo) {
        if (!$fileinfo->isDot()) {
            unlink( $fileinfo->getFilename() );
        }
    }
    

    Thank you for your answers, it's late here, it helped me think!


  2. No, none of these function throw an exception, so no exception will ever be caught by this code. unlink returns true or false, so the result of array_map will be an array of true and/or false values, and you need to test whether all values in the array are true to know whether all unlink operations succeeded.

    For this kind of operation, array_reduce is actually the better option, as it allows you to reduce the result to a single value right while you’re iterating:

    $result = array_reduce(glob('...'), fn($res, $file) => unlink($file) && $res, true);
    
    if (!$result) {
        echo "Something didn't get deleted!";
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search