tatty27
tatty27

Reputation: 1554

Get highest numbered file and create next one

I have a folder that contains files named standard_xx.jpg (xx being a number)

I would like to find the highest number so that I can get the filename ready to rename the next file being uploaded.

Eg. if the highest number is standard_12.jpg $newfilename = standard_13.jpg

I have created a method to do it by just exploding the file name but it isn't very elegant

$files = glob($uploaddir.'test-xrays-del/standard_*.JPG');
$maxfile = $files[count($files)-1];
$explode = explode('_',$maxfile);
$filename = $explode[1];
$explode2 = explode('.',$filename);
$number = $explode2[0];
$newnumber = $number + 1;
$standard = 'test-xrays-del/standard_'.$newnumber.'.JPG';
echo $newfile;

Is there a more efficient or elegant way of doing this?

Upvotes: 1

Views: 617

Answers (4)

SDC
SDC

Reputation: 14222

Something like this:

function getMaxFileID($path) {
    $files = new DirectoryIterator($path);
    $filtered = new RegexIterator($files, '/^.+\.jpg$/i');
    $maxFileID = 0;

    foreach ($filtered as $fileInfo) {
        $thisFileID = (int)preg_replace('/.*?_/',$fileInfo->getFilename());
        if($thisFileID > $maxFileID) { $maxFileID = $thisFileID;}
    }
    return $maxFileID;
}

Upvotes: 0

hakre
hakre

Reputation: 198119

You can make use of sscanfDocs:

$success = sscanf($maxfile, 'standard_%d.JPG', $number);

It will allow you to not only pick out the number (and only the number) but also whether or not this worked ($success).

Additionally you could also take a look into natsortDocs to actually sort the array you get back for the highest natural number.

A complete code-example making use of these:

$mask   = 'standard_%s.JPG';
$prefix = 'test-xrays-del';    
$glob   = sprintf("%s%s/%s", $uploaddir, $prefix, sprintf($mask, '*'));
$files  = glob($glob);
if (!$files) {
    throw new RuntimeException('No files found or error with ' . $glob);
}

natsort($files);

$maxfile = end($files);
$success = sscanf($maxfile, sprintf($mask, '%d'), $number);
if (!$success) {
    throw new RuntimeException('Unable to obtain number from: ', $maxfile);
}

$newnumber = $number + 1;
$newfile   = sprintf("%s/%s", $prefix, sprintf($mask, $newnumber));

Upvotes: 2

Dale
Dale

Reputation: 10469

I'd do it like this myself:

<?php

    $files = glob($uploaddir.'test-xrays-del/standard_*.JPG');
    natsort($files);
    preg_match('!standard_(\d+)!', end($files), $matches);
    $newfile = 'standard_' . ($matches[1] + 1) . '.JPG';
    echo $newfile;

Upvotes: 2

hsz
hsz

Reputation: 152266

Try with:

$files   = glob($uploaddir.'test-xrays-del/standard_*.JPG');
natsort($files);
$highest = array_pop($files);

Then get it's number with regex and increase value.

Upvotes: 1

Related Questions