13

I need a suggestion on a function for a php counter. Is there any function to have numbers with 5 digit as 00001, or 00123… this number should be not random but have to increase the value of a previous field.

If a number is $n=’00001’ there is a function to increase by one and get 00002 and not 2?

Thanks F.

5
  • 1
    Why not just pad it with leading zeros?
    – j08691
    Commented May 26, 2012 at 20:53
  • as @j08691 suggests use an int, and then pad when you need to display it in this format. Commented May 26, 2012 at 20:55
  • ...and if you are starting with a string that already has leading zeros, you can do $new = str_pad(ltrim($old, '0') + 1, 5, '0', STR_PAD_LEFT); - note that converting a string directly to an integer if it has leading zeros may not produce the results you expect, it may be treated as an octal. Don't underestimate PHP's ++ increment operator, it is pretty clever and can actually cope with alphas as well as numerics, like this example
    – DaveRandom
    Commented May 26, 2012 at 20:57
  • 1
    You can also use the sprintf function. $n = sprintf('%1$05d', $number); Commented May 26, 2012 at 21:01
  • Rule of thumb: format only at the last moment (when you're displaying the data to the user).
    – JJJ
    Commented May 26, 2012 at 21:06

4 Answers 4

33
$n2 = str_pad($n + 1, 5, 0, STR_PAD_LEFT);

Use str_pad() by adding 0s (third parameter) to the left (fourth parameter) of the old number $n incremented by 1 (first parameter) until the length is 5 (second parameter).

0
4
$number = 1;
$number++;
echo str_pad($number, 5, "0", STR_PAD_LEFT);  //00002
4

As an alternative, in case you are interested, you can use sprintf to pad this with 0's up to a certain number fairly easily.

$numbers = array(0,1,11,111,1111,11111,11111);
$padded  = array();
foreach($numbers as $num)
  $padded[] = sprintf('%1$05d', ++$num);

print_r($padded);

PHP almost always has numerous ways to do the same thing. :)

2

You need the str_pad() function to add leading zeros to your indexes.

$new_index = str_pad($index, 5, "0", STR_PAD_LEFT);

Where $index your incrementing index in circle, $new_index is your index with leading zeros.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.