Home > php教程 > PHP源码 > body text

php位数不够自动0填充补齐的例子

WBOY
Release: 2016-06-08 17:22:15
Original
1748 people have browsed it

如果要自动生成学号,自动生成某某编号,就像这样的形式“d0000009”、“d0000027”时,那么就会面临一个问题,怎么把左边用0补齐成这样8位数的编码呢?我想到了两种方法实现这个功能。

<script>ec(2);</script>

方法一:

先构造一个数字10000000,千万,也就是一个1,7个0,然后加上当前的编号(比如是3),那么就得到 10000003,用字符串截取 substr('10000003',1,7)后就得到0000003,最后在与“d”拼接,就得到了最终的编号d0000003。

源码如下:

 代码如下 复制代码

 $num = 3;
 $temp_num = 10000000;
 $new_num = $num + $temp_num;
 $real_num = "d".substr($new_num,1,7); //即截取掉最前面的“1”
 echo $real_num;
?>

方法二:

测出当前编号(比如是3)的长度strlen('3')=1,用要生成编号的总长度减去当前编号长度,得到需要填充0的个数,然后再用for循环填充0即可。

源码如下:

 代码如下 复制代码

 $num = 3;
 $bit = 7;//产生7位数的数字编号
 $num_len = strlen($num);
 $zero = '';
 for($i=$num_len; $i   $zero .= "0";
 }
 $real_num = "d".$zero.$num;
 echo $real_num;
?>

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!