0

I am using scandir to list the files. I get below array list

Code:

$dir = array_slice(scandir(\Yii::getAlias('@frontend/web/ads/')), 2);
print_r($dir);

Actual Output:

Array ( [0] => IX [1] => V [2] => VI [3] => VII [4] => VIII [5] => X [6] => XI ) 

Expected Output:

Array ( [0] => V [1] => VI [2] => VII [3] => VIII [4] => IX [5] => X [6] => XI ) 

Problem:

I created directories in order as V, VI, VII and so on. How can I arrange the files in the order they were created in PHP?

Ankur Soni
  • 5,725
  • 5
  • 50
  • 81
  • 1
    I think you want to sort your Array by roman numbers. Here you can find an answer http://stackoverflow.com/questions/6507536/how-to-sort-an-array-of-roman-numerals – Oliver Mar 02 '17 at 11:24
  • You have to sort the files, obviously. The documentation of the `scandir()` function clearly explaihs that: http://php.net/manual/de/function.scandir.php – arkascha Mar 02 '17 at 11:24
  • No that is secondary case. I want to sort files in the order they were created. – Ankur Soni Mar 02 '17 at 11:25
  • 1
    you cannot get date_created of a file. But you can get the date on which the file was last updated... If you want to have date_created, you can name the file with timestamp of date of creation. – meen Mar 02 '17 at 11:26

1 Answers1

0

You could just use usort to sort the array by file creation date

i.e.

$path = ...
usort($dir, function($a, $b) use ($path) {
    return filectime($path . $b) - filectime($path . $a);
});
Philipp
  • 15,377
  • 4
  • 35
  • 52
  • 2
    `filemtime — Gets file modification time`. No creation time.Here is the source of this info :http://php.net/manual/en/function.filemtime.php – meen Mar 02 '17 at 11:29
  • I think this does not work for directories except you add a dot at the and of the path. eg. filemtime($path.$b."/.") – Oliver Mar 02 '17 at 11:29
  • 1
    Sorry - it should be `filectime` - on windows it returns what you want and on unix, it returns the best you could get – Philipp Mar 02 '17 at 12:03