May 24, 2012
Numbering with prefix of zero in PHP
Question by Juvar Abrera
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 🙂
Answer by Starx
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);