Home >Backend Development >PHP Tutorial >Use PHP to add zeros to the front of a specified number
PHP adds zeros to the front of the number and 0 to the fixed number of digits
When designing a unique number, a fixed number of digits is required, for example, a fixed four-digit format is required:
For example:
YSZC After 0001, the following set of numbers, how to make it increase automatically?
1->0001 56->0056 288->0288 1992->1992
We can use the PHP built-in function str_pad () function to pad the string to the new length.
str_pad(string,length,pad_string,pad_type) //参数 描述 string //必需。规定要填充的字符串。 length //必需。规定新的字符串长度。如果该值小于字符串的原始长度,则不进行任何操作。 pad_string //可选。规定供填充使用的字符串。默认是空白。 pad_type //可选。规定填充字符串的哪边。 //可能的值: STR_PAD_BOTH - //填充字符串的两侧。如果不是偶数,则右侧获得额外的填充。 STR_PAD_LEFT - //填充字符串的左侧。 STR_PAD_RIGHT - //填充字符串的右侧。默认。
For example, I wrote a method to first determine whether there is data in the data table. If not, initialize 0001, otherwise call the auto-increment ID.
/** * @desc 协议编号 * @author 磊丰 * @Date 2021/12/1 16:23 * @param $num * @return string */ public function inc_privacy_no($num) { $start = "0001"; $data = 表::find('id'); //这里是查询表里的一条最新的sql数据,自己写 if(empty($data)){ return $num.$start; } $data_no = str_pad(($data['id']+1),4,"0",STR_PAD_LEFT); return $num.$data_no; }
Calling method
$this->inc_privacy_no("YSZC")
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of Use PHP to add zeros to the front of a specified number. For more information, please follow other related articles on the PHP Chinese website!