Forum Moderators: coopster

Message Too Old, No Replies

Count loop with zero's

How to number files in a loop

         

wheelie34

10:33 am on Nov 7, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi all

I have an image upload script that loops through and assigns numbers to each image, it works perfect BUT I have added a display order to the database entry to keep them in the order I want them however, if I upload 10 images obviousley the display order now returns 1, 10, 2 as theres no zero before the single diget images, heres my code

for ($i=1;$i<11;$i++)
{
$thepic="pic".$i;
if (($$thepic<>"none") and ($$thepic<>""))
{
$dest="../folder_name/images/".$insid."-".$i.".jpg

$sql = "insert into images values('', '$insid-$i.jpg', '$insid', '$i')";

I tried adding the zero to $i=01 but it didnt do as wanted, the column for display order is a varchar if that helps.

Thanks

adb64

11:00 am on Nov 7, 2006 (gmt 0)

10+ Year Member



Use sprintf [php.net] to add leading zeros.
So you could do something like:

$name = sprintf("%s-%03d.jpg",$insid,$i);
$dest="../folder_name/images/$name";

In this case the %03d will do the trick, it will print the number always with 3 digits and pad it with zeros when number not large enough to take up 3 digits.
Use %02d if you need 2 digits etc.
You may also want to take a look at the str_pad [php.net] function.