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.
Input :1234567 Output :01234567 Input :1234 Output :00001234
Using sprintf() Function: The sprintf() function is used to return a formatted string.
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.
- Example 2: This example uses sprintf() function to display negative numbers with leading zeros.
- 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:
Using substr() Function: This function is used to return part of a string.
substr( string $string , int $start, int $length ) // Returns the portion of string that define at start and length of the parameter.