By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,722 Members | 1,904 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,722 IT Pros & Developers. It's quick & easy.

4 digit number

P: 563
Hii guys,
I am generating a ID for students and i want the Id to be 4 digit always .....I keep incrementing the ID's .so it must automatically put 0's behind the number to make it 4 digit....How to do it...
Oct 3 '08 #1
Share this Question
Share on Google+
3 Replies

P: 258
You can not use a numerical variable because PHP will automaticaly delete extra zeros on the left side of your variable.

But you can use a string like this:

Expand|Select|Wrap|Line Numbers
  1. <?PHP
  2.     $var=123;
  3.     $fourDigit = trim($var);
  4.     for ($i=0; $i<=3; $i++) {
  5.         if (strlen($fourDigit) < 4) {$fourDigit = "0".$fourDigit;}
  6.     }
  7.     echo $fourDigit;
  8. ?>
The length of your string will allways be 4 as long as you use numbers less than 10000

Hope it helps
Oct 3 '08 #2

Expert 5K+
P: 5,058
Why don't you just start counting at 1000?

Or, if you are using a database, like MySQL, you can have the database automatically add zeros to have the number fill a given length.

From the MySQL manual:
When used in conjunction with the optional extension attribute ZEROFILL, the default padding of spaces is replaced with zeros. For example, for a column declared as INT(5) ZEROFILL, a value of 4 is retrieved as 00004.
Oct 4 '08 #3

P: 563
thank you bnashenas1984.that worked for me..i was using a similar kind of script but for 0 i was not using "0" i was just using 0 that caused me problem.

Oct 4 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.