Skip to content
Related Articles

Related Articles

Improve Article

Format a number with leading zeros in PHP

  • Last Updated : 22 Jun, 2021

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 formated 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

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :