How to format a number with leading zeros in PHP?

In my application, I want to generate auto-increment numbers starting from 1, 2, 3, etc. I have a MySQL column where I can get the number. But the problem is the number should be 4 digits if the number is 1 then it should look like 0001 and if it’s 2 then it should be 0002. it’s fine if the number is more than 4 digits.

So how do I add zeros in front of numbers in PHP?

You can use sprintf() function. The function accepts 2 parameters. The first one is the format and the second one is the number.

echo sprintf(format, number);

For your need, you need to use %04d for format.

$number = 1;
echo sprintf('%04d', $number );
// 0001
You can also use **str_pad()** to do this.
$number = 1;
echo str_pad($number, 4, '0', STR_PAD_LEFT);
// 0001