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 formated according to the format provided.
-
Example 1: This example uses sprintf() function to dispaly the number with leading zeros.
<?php$var= 1234567;echosprintf('%08d',$var);?>chevron_rightfilter_noneOutput:
01234567
-
Example 2: This example uses sprintf() function to display negative numbers with leading zeros.
<?php$var1= -10;$var2= 10;echosprintf('%04s',$var1) ."\n";echosprintf('%04s',$var2);?>chevron_rightfilter_noneOutput:
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$var1= -10;$var2= 10;echosprintf('%04d',$var1) ."\n";echosprintf('%04d',$var2);?>chevron_rightfilter_noneOutput:
-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 $num = 123; $str_length = 4; // Left padding if number < $str_length $str = substr("0000{$num}", -$str_length); echo sprintf($str); ?> |
Output:
0123
Recommended Posts:
- JavaScript | Pad a number with leading zeros
- How to remove all leading zeros in a string in PHP ?
- How to format a phone number in Human-Readable using JavaScript ?
- Node | URL.format API
- PHP | Format Specifiers
- How to format a float in JavaScript ?
- PHP | DateTime format() Function
- Node | URL.format(urlObject) API
- PHP | IntlDateFormatter format() Function
- PHP program to change date format
- PHP date() format when inserting into datetime in MySQL
- How to print an array in table format using angularJS?
- How to format numbers as currency string in JavaScript ?
- How do you display JavaScript datetime in 12 hour AM/PM format?
- How to get Month and Date of JavaScript in two digit format ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



