Search code examples
phpglobscandir

How to identify in the directory the file with higher numbering and save in a variable?


I have in a folder named files sequentially

file1
file2
file3

I know glob or scandir can list the files in a directory, but how would it be possible to identify the most current file (numbering) to sequence and save the next files with correct numbering?

summarizing: how to identify with PHP the file with higher number and save this in a variable?


Solution

    • You can get the newest file from the directory.
    • Remove 'file' substring from the file name, to get the last file number
    • Increment the number and do string operations to get your new filename.

    Try the following:

    // $directory_path is the directory you are scanning
    // Scan directory in descending order
    $files = scandir($directory_path, SCANDIR_SORT_DESCENDING);
    $last_file = $files[0];
    
    // extract the last file number
    $last_file_no = (int)str_replace('file', '', $last_file);
    
    // prepare the new file name
    $new_file_no = $last_file_no + 1;
    $new_file_name = 'file'. $new_file_no;