業務系統中常需生成固定長度的編碼:會員卡號、訂單號、員工工號、發票代碼等。str_pad() 是 PHP 內建的最佳工具,支援左右填充、自定義填充字符、長度控制。
str_pad(string $string, int $length, string $pad_string = " ", int $pad_type = STR_PAD_RIGHT): string
| 常量 | 行為 | 示例 |
|---|---|---|
STR_PAD_LEFT | 左側填充 (補零常用) | str_pad('1', 5, '0', STR_PAD_LEFT) → 00001 |
STR_PAD_RIGHT | 右側填充 (默認) | str_pad('1', 5, '0', STR_PAD_RIGHT) → 10000 |
STR_PAD_BOTH | 兩側填充,右側優先 | str_pad('1', 5, '0', STR_PAD_BOTH) → 00100 |
<?php
$cardCount = 10;
$cards = [];
for ($i = 1; $i <= $cardCount; $i++) {
// 關鍵:STR_PAD_LEFT 實現左側補零
$cards[] = str_pad((string)$i, 10, '0', STR_PAD_LEFT);
}
print_r($cards);
/*
Array
(
[0] => 0000000001
[1] => 0000000002
[2] => 0000000003
[3] => 0000000004
[4] => 0000000005
[5] => 0000000006
[6] => 0000000007
[7] => 0000000008
[8] => 0000000009
[9] => 0000000010
)
*/
<?php
class CodeGenerator {
public static function generate(
int $sequence,
int $length = 10,
string $prefix = '',
string $suffix = '',
string $padChar = '0'
): string {
if ($length < 1) throw new InvalidArgumentException('長度必須大於 0');
if (mb_strlen($padChar) !== 1) throw new InvalidArgumentException('填充字符必須為單字符');
$numStr = (string)$sequence;
if (mb_strlen($numStr) > $length) {
throw new OverflowException("序列號 $sequence 超過最大長度 $length");
}
$padded = str_pad($numStr, $length, $padChar, STR_PAD_LEFT);
return $prefix . $padded . $suffix;
}
public static function batchGenerate(
int $start,
int $count,
int $length = 10,
string $prefix = '',
string $suffix = ''
): array {
$codes = [];
for ($i = 0; $i < $count; $i++) {
$codes[] = self::generate($start + $i, $length, $prefix, $suffix);
}
return $codes;
}
}
// 使用示例
$cards = CodeGenerator::batchGenerate(1, 1000, 8, 'VIP', '');
// 生成:VIP00000001, VIP00000002, ..., VIP00001000
$orders = CodeGenerator::batchGenerate(10000, 500, 12, 'ORD-', '-CN');
// 生成:ORD-0000010000-CN, ORD-0000010001-CN, ...
| 場景 | 長度 | 前綴 | 填充字符 | 示例 |
|---|---|---|---|---|
| 會員卡號 | 10-16 | VIP/MC | 0 | VIP0000001234 |
| 訂單號 | 12-18 | ORD/OD | 0 | ORD202401150001 |
| 員工工號 | 6-8 | EMP/工 | 0 | EMP000123 |
| 發票代碼 | 10-12 | INV/發 | 0 | INV0000000456 |
| 優惠券碼 | 8-12 | COUPON | 0/A-Z | COUPON000ABC |
<?php
// 百萬級生成:避免循環調用函數開銷
function generateCodesVectorized(int $start, int $count, int $length, string $padChar = '0'): array {
$format = "%0{$length}s"; // sprintf 格式化,比 str_pad 快 ~20%
$codes = [];
for ($i = 0; $i < $count; $i++) {
$codes[] = sprintf($format, $start + $i);
}
return $codes;
}
// 基準測試 (100萬次)
$start = microtime(true);
$codes1 = [];
for ($i = 1; $i <= 1000000; $i++) {
$codes1[] = str_pad((string)$i, 10, '0', STR_PAD_LEFT);
}
echo "str_pad: " . (microtime(true) - $start) . "s\n"; // ~0.45s
$start = microtime(true);
$codes2 = generateCodesVectorized(1, 1000000, 10);
echo "sprintf: " . (microtime(true) - $start) . "s\n"; // ~0.38s
str_pad('1', 5, '00') 會重複 '00' 導致長度不可控 → 強制單字符str_pad(1.5, 5, '0') → 001.5 → 強制轉整數字符串<?php
function toBase36(int $num): string {
$chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$result = '';
while ($num > 0) {
$result = $chars[$num % 36] . $result;
$num = (int)($num / 36);
}
return $result ?: '0';
}
function generateShortCode(int $seq, int $length = 8): string {
$base36 = toBase36($seq);
return str_pad($base36, $length, '0', STR_PAD_LEFT);
}
// 1000000 → 000LFLS (6位) vs 0000001000000 (13位),節省 54% 長度
str_pad 是生成固定長度編碼的標準工具。封裝通用生成器、處理邊界條件、考慮併發與效能,能構建穩定可靠的業務編碼系統。