4 digit number

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pradeepjain
    Contributor
    • Jul 2007
    • 563

    4 digit number

    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...
  • bnashenas1984
    Contributor
    • Sep 2007
    • 257

    #2
    Hi
    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:

    Code:
    <?PHP
    	$var=123;
    	$fourDigit = trim($var);
    	for ($i=0; $i<=3; $i++) {
    		if (strlen($fourDigit) < 4) {$fourDigit = "0".$fourDigit;}
    	}
    	echo $fourDigit;
    ?>
    The length of your string will allways be 4 as long as you use numbers less than 10000

    Hope it helps

    Comment

    • Atli
      Recognized Expert Expert
      • Nov 2006
      • 5062

      #3
      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:
      Originally posted by dev.mysql.com
      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.

      Comment

      • pradeepjain
        Contributor
        • Jul 2007
        • 563

        #4
        thank you bnashenas1984.t hat 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.


        thanks,
        Pradeep

        Comment

        Working...