Add Leading Zeroes in PHP
Learn how to easily add leading zeroes to numbers in PHP with the str_pad() function. Make your numbers consistent and tidy!
To add one leading zero to a number in PHP, you can use the native str_pad()
PHP function. This function takes the input string of the number, the desired length of the output string, and the character to use as padding (in this case, 0
), and returns the padded string.
PHP Leading Zeroes Example
Here is an example:
$num = 5; // input number $output = str_pad($num, 3, '0', STR_PAD_LEFT); // a total of 3 digits echo $output; // outputs "005"
This is an explanation of the example above:
- The input number is set to
5
-
We then use the
str_pad()
function to add two leading zeros to this number. The desired length of the leading zeroes is specified to3
to account for the added zeroes, and the padding character is set to0
. -
We also use the
STR_PAD_LEFT
option ofstr_pad()
to specify that the padding should be applied to the left of the input string. You can also useSTR_PAD_RIGHT
to append them to the end of your string instead. - Finally, we output the padded string, which is
005
.
It's easier than you might think to add those leading zeroes to your numbers using PHP and the built-in str_pad()
function!
Details
- Title: Tutorial: Add Leading Zeroes in PHP
- Published:
- Author: Andrew Young
- Categories: PHP