How to properly Format a Number With Leading Zeros in PHP ?
A number is essentially a sequence of digits stacked together to form an integer or string. A number can begin with leading zeros. A number can also be looped through and modifications can be made to append or concatenate another sequence of characters into it.
Approach 1: Using a for loop for string concatenation
A for loop can be iterated where the no. of iterations is equivalent to the number of zeros to lead the number with. During each iteration, a zero is appended to the front of the string. The time complexity is linear in terms of the number of zeros and is assumed to be constant for all practical purposes.
Original number : 999 Modified number : 0000999
Approach 2: Conversion of integer to string
A string variable can be used as a substitute for storing numbers. The length of the number doesn’t have to be specified explicitly. PHP automatically coerces the type of the stored number. Also, explicit change of data types can be made by casting the type into the required format.
However, the numeric data types have a limitation of storing the numbers without any leading zeros, therefore, all the zeros are removed as soon as the casting is done. The below code snippet illustrates this procedure.
Original Number 00000092939292 explicit casting. 92939292
Approach 3: Using str_pad() method
This method will pad a string to a new length of the specified characters. In this case, the number is declared using a string variable. If the specified length is less than or equal to the original length of the string, no modifications are made to the original string. The str_pad() method is another alternative to performing repeated string concatenation.
In this approach, we will use left padding to pad the string from left-hand side. The pad_type will be STR_PAD_LEFT and the pad_string will be equivalent to “0”. The length is equivalent to the length of the original string added to the number of zeros we wish to lead the number with.
Original String 2222 Modified String 00002222
Approach 4: Using format specifiers printf()/sprintf()
The printf() and sprintf() functions both results in a formatted string. A format is specified to output the number based on the leading character and the total length of the string. It is necessary to indicate the type of the number, that is, whether it is decimal, hexadecimal or octal, or so on. It is used to modify the number in such a way as to reflect the proper pattern of the number. At least one of the arguments is mandatory while calling this function.
- format (Required ): The string which format the variables.
- arg1: A value to be inserted at the first % sign
- arg2 (Optional): A value to be inserted at the second % sign
Original Number : 86857658 <br>Modified Number : 000000000086857658