Read files in a directory sorted by creation date

Asked

Viewed 170 times

5

I have the following code to include all PHP files I find in a directory:

if (is_dir(CONF_REL_PATH_BANANAS)) {
  foreach (glob(CONF_REL_PATH_BANANAS.'/*.php') as $file) {
    require_once($file);
  }
}

When sending the files there, I was careful to create them in the order I wanted them to be loaded, but the result is:

array(7) {
  [0]=>
  string(29) "caminho/para/bananas/campaign.php"
  [1]=>
  string(29) "caminho/para/bananas/contacts.php"
  [2]=>
  string(29) "caminho/para/bananas/homepage.php"    // este seria o primeiro
  [3]=>
  string(32) "caminho/para/bananas/participate.php"
  [4]=>
  string(29) "caminho/para/bananas/partners.php"
  [5]=>
  string(28) "caminho/para/bananas/picking.php"
  [6]=>
  string(28) "caminho/para/bananas/results.php"
}

That is, the files are appearing sorted alphabetically.

Known solution

Manipulating the filenames easily solves the problem:

array(7) {
  [0]=>
  string(31) "caminho/para/bananas/1_homepage.php"
  [1]=>
  string(31) "caminho/para/bananas/2_campaign.php"
  [2]=>
  string(34) "caminho/para/bananas/3_participate.php"
  [3]=>
  string(30) "caminho/para/bananas/4_picking.php"
  [4]=>
  string(31) "caminho/para/bananas/5_partners.php"
  [5]=>
  string(30) "caminho/para/bananas/6_results.php"
  [6]=>
  string(31) "caminho/para/bananas/7_contacts.php"
}

But this raises maintenance issues and future additions of new files.

Question

How can I read existing files in a directory by getting them sorted by their creation date ?

  • I’ve been preparing an entire answer, but then I realized that your question called for ordination by creation date. Sorry. :) Well, still trying to help, this question in the English OS may be useful: http://stackoverflow.com/questions/2667065/sort-files-by-date-in-php

1 answer

1

You won’t be able to make use of the function scandir() directly, but in this way:

$arquivos = glob('/pasta/*');
usort($arquivos, function($a, $b) {
    return filemtime($a) < filemtime($b);
});


//print_r($arquivos);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.