What are the best practices for creating a multidimensional array with file names and modification dates, sorting it, and displaying the x most recent entries in PHP?
To create a multidimensional array with file names and modification dates, sort it based on the dates, and display the x most recent entries in PHP, you can use the following approach: 1. Use the scandir() function to get a list of files in a directory. 2. Iterate over the list of files, storing the file name and modification date in a multidimensional array. 3. Sort the array based on the modification dates in descending order. 4. Display the x most recent entries by iterating over the sorted array and outputting the file names.
<?php
$directory = 'path/to/directory';
$files = scandir($directory);
$fileData = [];
foreach ($files as $file) {
if ($file !== '.' && $file !== '..') {
$fileData[$file] = filemtime($directory . '/' . $file);
}
}
arsort($fileData);
$x = 5; // Number of most recent entries to display
$count = 0;
foreach ($fileData as $file => $date) {
echo $file . ' - ' . date('Y-m-d H:i:s', $date) . "\n";
$count++;
if ($count >= $x) {
break;
}
}
?>