網頁

2013年2月25日

[php] fillzero數字不足位數補零

主要用途:
產生固定長度流水號。

指令範例:
echo fillzero(32, 10);

執行結果:
0000000032

參數說明:
$integer 流水號
$limit 長度
function fillzero ($integer, $limit = 2)
{
    if (is_numeric($integer)){
        return sprintf("%0".$limit."d", $integer);
    }
}

使用str_pad填充功能,也可以達到補零功能。

程式範例:
<?php
$input = 32;
echo str_pad($input, 10, 0);  //右邊補零
echo str_pad($input, 10, 0, STR_PAD_LEFT);  //左邊補零
echo str_pad($input, 10, 0, STR_PAD_BOTH);  //中間補零
?>


執行結果:
3200000000
0000000032
0000320000