There are at least two functions in PHP that can help us quickly implement zero-padding:
The first is the PHP str_pad function:
Copy codeThe Code is as follows: # str_pad-Use another string to fill the string with the specified length
As the name implies, this function is intended for strings and fills in any other strings for the specified string.
Str_pad parameter description:
Copy codeThe Code is as follows: string str_pad (string $ input, int $ pad_length [, string $ pad_string = "" [, int $ pad_type = STR_PAD_RIGHT])
# Description of common parameters: str_pad (string with padding, the length after filling, the string to fill, and the position to fill)
The length after filling must be a positive integer and there are three options to fill the position,
Left: STR_PAD_LEFT
Right: STR_PAD_RIGHT
Two ends: STR_PAD_BOTH
Instance display:
Copy codeThe Code is as follows: echo str_pad (1,8, "0", STR_PAD_LEFT );
# Result: 00000001
Echo str_pad (1,8, "0", STR_PAD_RIGHT );
# Result: 10000000
Echo str_pad (1,8, "0", STR_PAD_BOTH );
# Result: 00010000
In the above example, it is worth noting that if the number of digits to be filled is an odd number, for example, if the number of digits to be filled is 7 in the third case, the right side is given priority.
Next, let's look at another method to add zero:
PHP sprintf function:
Copy codeThe Code is as follows: # sprintf-returns a formatted string
This function is flexible to use and needs to be explored by scholars. Here we mainly discuss how to add zeros to the left of the value (or add zeros after the decimal point;
First look at the left zero
Copy codeThe Code is as follows: echo sprintf ("% 05d", 1 );
# % 05d: format the following parameter with a 5-digit number. If there are less than five digits, add zero.
# The running result is 00001.
Then add zero after the decimal point.
Copy codeThe Code is as follows: echo sprintf ("% 01.3f", 1 );
# % 01.3f: Use a floating-point number with at least three digits after the decimal point to complete zero, at least one digit before the decimal point, and less than one complement zero to format the following parameters.
# Running result: 1.000
You can also compile a UDF for processing;
Code writing is both superior and inferior. You can choose the appropriate one;
Note: sprintf can ensure that 1 is not supplemented into 1000000 by misoperations, and str_pad can ensure that what needs to be supplemented.