在PHP中使用前缀零编号

Is it possible in PHP to echo out a number with zeroes at the beginning?

For example

<?php

$i = 0001;
$i++;
echo $i;

?>

And when it print out, I want it to be like.

0002

Is it possible? Thanks :)

Yes, it is possible. You can do this using str_pad() method. Basically, this method adds a given value till a required length is achieved.

A Basic example of this would be:

echo str_pad($i, 4, "0", STR_PAD_LEFT); 

Here,

  • 4 represents the output length
  • "0" represents the string used to pad, till the length is achieved.

Demo Example:

<?php
$i = 0001;
$i++;
echo str_pad($i, 4, "0", STR_PAD_LEFT);
$i = 1;
$i++;
printf("%04d", $i); // 0002
  • printf - output a formatted string
  • %04d - echo a 4 digit number, pad with 0's

try this

echo str_pad($i, 4,"0",STR_PAD_LEFT);

read the documentation here : http://php.net/manual/en/function.str-pad.php

$input = 0001;
echo str_pad(++$input, 4, "0", STR_PAD_LEFT);