0

I have the following PHP code to rename pictures sequentially:

function sequentialImages($path) {
 $i = 1;
 $files = glob($path."/{*.gif,*.jpg,*.jpeg,*.png}",GLOB_BRACE|GLOB_NOSORT);
  $count = count($files);
 foreach ( $files as $file ) {
  $newname = str_pad($i, strlen($count)+1, '0', STR_PAD_LEFT);
  $ext = substr(strrchr($file, '.'), 1);
  $newname = $path.'/pictures'.$newname.'.'.$ext;
  if ( $file != $newname ) {
   rename($file, $newname);  
  }
  $i++;
 }
}

I would like to rename

01.jpg to picture01.jpg
02.jpg to picture02.jpg
03.jpg to picture03.jpg
04.jpg to picture04.jpg
.....
10.jpg to picture10.jpg
11.jpg to picture11.jpg

The output I am getting is

pictures001.jpg
pictures002.jpg
pictures003.jpg
pictures004.jpg
....
pictures010.jpg
pictures011.jpg

I would like that if the image sequence is less than 9 it will have a '0' before it. If it is 10 or more it won't have that extra zero.

I tried adding

for ($i=1; $i<=21; $i++)  {
    if($i<=9) {
        //code
    }
    else {
        //code
    }
}

but it didn't work either.

user3173207
  • 269
  • 1
  • 7
  • 21

1 Answers1

2

If you want to use str_pad and you are staying under 99 files, then you should hardcode the length you want to pad to.

$newname = str_pad($i, 2, '0', STR_PAD_LEFT);

Of course, as Loz Cherone correctly mentioned, the better way to do this is to use sprintf.

sprintf("%02d", $i)
merlin2011
  • 71,677
  • 44
  • 195
  • 329