branco holtslag
branco holtslag

Reputation: 279

Scandir() to show the newest folder

I basically have a form that creates a folder when submitted, it takes the last created folder (for example the folder name is 7) and creates a new map based on the last created folder (7+1) thus making a new folder named 8 etc. etc.

However when I create a map with the name 10 and echo $latest_dir it will still show 9.. whilst it should just show the highest number at all times.

$maindir = scandir("uploads/");
$latest_dir = $maindir[0];
$new_dir = $latest_dir+1;

echo $latest_dir;

I'm not really that good with PHP and this is the only thing that is not working so far.

Upvotes: 1

Views: 160

Answers (2)

branco holtslag
branco holtslag

Reputation: 279

I got the problem fixed, the folders were not ordered correctly, I changed my code to this:

$maindir = scandir("uploads/",1);
rsort($maindir);
$latest_dir = $maindir[0];
$new_dir = $latest_dir+1;

It orders the folders correctly and always shows the highest folder name. Thanks for everyone's help :)

Upvotes: 0

Mathieu Bertin
Mathieu Bertin

Reputation: 1624

This is my code, I don't have tested it but I think it works.

$maindir = scandir("uploads/");

//remove '.' and '..' folder you can also use a regex to be sur to have only folder with
// number after filter
$mainDir = array_filter($maindir, function ($fileName) {
   if ($fileName !== "." || $fileName !== "..") {
      return TRUE;
   }
   else {
      return FALSE;
   }
}

$maxNumber = 0;

// Browse the array in order get the highest number (maybe you could use natsort() instead
for($i = 0 ; $i < count($mainDir) ; $i++) {
   if($maxNumber > (int) $mainDir[i]) {
      $maxNumber = (int) $mainDir[i];
   }
}

$new_dir = $maxNumber + 1;

Upvotes: 0

Related Questions