3 digit number in PHP

They have: 3 posts

Joined: Nov 2003

Hi,

I want to create a file which includes a three digit number. For example, file001.txt, file021.txt etc.

I have used the following code:

$ext = "txt";
$i = 004;
$TheFile = "file $i.$ext";

but $TheFile = "file4.txt"

How can I get $TheFile = "file004.txt" ?

Thank you.

Jan

druagord's picture

He has: 335 posts

Joined: May 2003

you have to use a string since int are alway striped of there 0

$ext = "txt";
for($i=1;$i<500;$i++)
{
   if($i>=100)
        $zero="";
   else if ($i>=10)
         $zero="0";
   else
         $zero="00";
   $TheFile = "file".$zero.$i.$ext";
}
'

IF , ELSE , WHILE isn't that what life is all about

They have: 3 posts

Joined: Nov 2003

Thank you for your help. I'm a PHP beginner and I came across the following solution which seems to work:

$i=str_pad($i,3, "0",STR_PAD_LEFT);

Is this a good solution? I am eager to learn!

druagord's picture

He has: 335 posts

Joined: May 2003

yes better then the one i gave you i just was too leazy to search for syntax

They have: 3 posts

Joined: Nov 2003

Thank you very much!

They have: 461 posts

Joined: Jul 2003

php.net

bokmark it.
always go there first for php questions. chances are it has the answer. if that doesn't succeed ask for clarificaton here or at the dev net (linked to there)

dev net seemsfaster but same quality for php responses. this is bettter for everything else.

they are by far the best stes i've found for help

POSIX. because a stable os that doesn't have memory leaks and isn't buggy is always good.

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

Even better:

<?php
$TheFile
= sprintf(\"file%3d.%s\", $i, $ext);
?>

druagord's picture

He has: 335 posts

Joined: May 2003

your the man Mark thanks for this recall of the c syntax that i forgot Smiling

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.