Friday, October 10, 2025
HomeLanguagesFormat a number with leading zeros in PHP

Format a number with leading zeros in PHP

Often times, while writing a code we face situations where we need to pad a numbers/strings and make them of a default length. In this article, we will learn how to pad a number with leading zeros in PHP. 
Here are few examples for the better understanding of the task.
Examples: 
 

Input :1234567
Output :01234567

Input :1234
Output :00001234

There are many ways to pad leading zeros in string format. But in case of string the best way to achieve the task is by using sprintf function and also you can use substr() function. 
 

Using sprintf() Function: The sprintf() function is used to return a formatted string. 
Syntax: 

sprintf(format, $variable)
// Returns the variable formatted according to the format provided. 

Example 1: This example uses sprintf() function to display the number with leading zeros.  

php




<?php
$var = 1234567;
echo sprintf('%08d', $var);
?>


Output: 

01234567

Example 2: This example uses sprintf() function to display negative numbers with leading zeros. 

php




<?php
$var1 = -10;
$var2 = 10;
echo sprintf('%04s', $var1) . "\n";
echo sprintf('%04s', $var2);
?>


Output: 

0-10
0010

In the above example, we tried to format the number as a string and messed up the negative. But that would not be the case if we format numbers using ‘%d’ rather than ‘%s’.

Example 3: 

php




<?php
$var1 = -10;
$var2 = 10;
echo sprintf('%04d', $var1) . "\n";
echo sprintf('%04d', $var2);
?>


Output:  

-010
0010

Using substr() Function: This function is used to return part of a string. 
Syntax:  

substr( string $string , int $start, int $length )
// Returns the portion of string that define at start and length of the parameter. 

Example: 

php




<?php
$num = 123;
$str_length = 4;
 
// Left padding if number < $str_length
$str = substr("0000{$num}", -$str_length);
echo sprintf($str);
?>


Output: 

0123
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32349 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6717 POSTS0 COMMENTS
Nicole Veronica
11880 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6838 POSTS0 COMMENTS
Ted Musemwa
7097 POSTS0 COMMENTS
Thapelo Manthata
6792 POSTS0 COMMENTS
Umr Jansen
6792 POSTS0 COMMENTS