Leading Zeros

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
spacebiscuit
Forum Contributor
Posts: 390
Joined: Mon Mar 07, 2005 3:20 pm

Leading Zeros

Post by spacebiscuit »

Hi,

I am trying to find a way of adding leading zeros to a number.

sprintf does not work because it always adds x number of zeros. This is no good in the following example:

9 becomes 0009
10 becomes 00010

10 should become 0010.

I hope that makes sense?

Rob.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Re: Leading Zeros

Post by superdezign »

spacebiscuit
Forum Contributor
Posts: 390
Joined: Mon Mar 07, 2005 3:20 pm

Re: Leading Zeros

Post by spacebiscuit »

Same problem..... it adds the same number of zeros to all cases.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Re: Leading Zeros

Post by superdezign »

Then you are doing it wrong.

Code: Select all

echo str_pad($input, 4, '0', STR_PAD_LEFT);
Also, it shouldn't make a difference, but make sure that $input is a string.
spacebiscuit
Forum Contributor
Posts: 390
Joined: Mon Mar 07, 2005 3:20 pm

Re: Leading Zeros

Post by spacebiscuit »

Maybe that is the problem - the input is not a string it is an int. The above example does not work.

Rob.
spacebiscuit
Forum Contributor
Posts: 390
Joined: Mon Mar 07, 2005 3:20 pm

Re: Leading Zeros

Post by spacebiscuit »

My error - str_pad does the trick. I just forgot to remove the leading 0 i had hardcoded into my my testing environment - opps!

Code: Select all

str_pad((int) $x,4,"0",STR_PAD_LEFT))
Many thanks,

Rob.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Leading Zeros

Post by requinix »

Post Reply