$filename, 'date' => $matches[1], // Extracted date as string YYYYMMDD ]; } } // Sort files by date descending (newest first) usort($matchedFiles, function($a, $b) { return strcmp($b['date'], $a['date']); // descending order by date string }); // Take only the latest $maxDays files $latestFiles = array_slice($matchedFiles, 0, $maxDays); // Extract only the filenames for JavaScript consumption $files = array_column($latestFiles, 'filename'); // Encode the list of files as JSON for frontend use $filesJson = json_encode(array_values($files));