PHP introduces two functions that implement the digit zero filling function. In PHP, there are at least two functions that can help us quickly implement zero-padding: The first is the PHPstr_pad function: Copy the code as follows: # str_pad-use another string to fill in characters. there are at least two functions in PHP that can help us quickly implement zero padding:
The first is the PHP str_pad function:
The 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:
The 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:
The 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:
The 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
The 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.
The 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.
Compile is the PHP str_pad function first: the code is as follows: # str_pad-use another string to fill the character...