printf() 直接輸出並返回長度;sprintf() 返回格式化字串不輸出。
| 函數 | 原型 | 返回值 | 副作用 |
|---|---|---|---|
printf | printf(string $format, mixed ...$values): int | 輸出字串的長度(位元組數) | 直接輸出到標準輸出 |
sprintf | sprintf(string $format, mixed ...$values): string | 格式化後的字串 | 無輸出,需自行 echo/存變數 |
fprintf | fprintf(resource $stream, string $format, mixed ...$values): int | 寫入長度 | 寫入指定資源(檔案/網路/標準錯誤) |
vprintf/vsprintf/vfprintf | 參數為陣列版本 | 同上 | 同上 |
%[參數][寬度][.精度]類型
| 類型 | 說明 | 範例輸出 |
|---|---|---|
% | 字面 % 符號 | %% → % |
b | 二進位 | %b (10) → 1010 |
c | ASCII 字元 | %c (65) → A |
d | 有號十進位 | %d (-10) → -10 |
e/E | 科學記號 | %e (1234) → 1.234000e+3 |
f/F | 浮點數(區域設定敏感) | %.2f (3.14159) → 3.14 |
g/G | 自動選擇 e/f 短者 | %g (1234) → 1234 |
o | 八進位 | %o (10) → 12 |
s | 字串 | %s ('abc') → abc |
x/X | 十六進位 (小寫/大寫) | %x (255) → ff |
u | 無號十進位 | %u (-1) → 4294967295 (32位) |
0:前導補零 %05d (7) → 00007-:左對齊 %-10s ('a') → 'a '+:強制顯示正負號 %+d (10) → +10 (空格):正數前加空格 % d (10) → 10'x:自定義填充字元 %'#10s ('a') → #########a<?php
$nums = [21, 16.3287, 32.12329, -5.555];
foreach ($nums as $n) {
// sprintf 返回字串,適合存入變數/資料庫/日誌
$formatted = sprintf('%0.2f', $n);
echo "$n → $formatted\n";
}
// 輸出:
// 21 → 21.00
// 16.3287 → 16.33
// 32.12329 → 32.12
// -5.555 → -5.56
<?php
$ts = time();
echo sprintf('%04d-%02d-%02d %02d:%02d:%02d',
date('Y', $ts), date('m', $ts), date('d', $ts),
date('H', $ts), date('i', $ts), date('s', $ts)
); // 2025-01-15 14:30:45
<?php
$table = 'users';
$id = 123;
$sql = sprintf('SELECT * FROM %s WHERE id = %d', $table, $id);
// 注意:%s 不會加引號,%d 會強制轉整數,防注入效果有限
<?php
function genOrderNo(int $seq): string {
return sprintf('ORD-%04d%06d', date('md'), $seq); // ORD-0115000123
}
<?php
$ptr = 0x7fffaabbccdd;
printf("Pointer: 0x%012X\n", $ptr); // Pointer: 0x007FFFAABBCCDD
$data = "ABC";
echo "Hex: " . bin2hex($data) . "\n"; // 414243
echo "sprintf: " . sprintf('%02X %02X %02X', ...unpack('C*', $data)) . "\n";
<?php
$fmt = 'User: %s, Age: %d, Score: %.2f';
$data = ['Alice', 25, 98.765];
// 100萬次迴圈
$t = microtime(true);
for ($i=0; $i<1_000_000; $i++) sprintf($fmt, ...$data);
echo "sprintf: " . (microtime(true)-$t) . "s\n"; // ~0.45s
$t = microtime(true);
for ($i=0; $i<1_000_000; $i++) printf($fmt, ...$data);
echo "printf: " . (microtime(true)-$t) . "s\n"; // ~0.55s (含輸出開銷)
// 結論:純格式化用 sprintf;直接輸出用 printf;差異微小,優先考慮語意
%d 遇到字串會轉 0 並發出 Warning;%f 遇到非數值同理。%10s 寬度以位元組計,中文 UTF-8 一字 3 位元組,顯示寬度會「短」於預期。需用 mb_strwidth 輔助或改用 mb_sprintf(需 polyfill)。sprintf('%.2f', 1.005) 可能得 1.00(二進位表示誤差),金融計算請用 bcmath 或整數分單位。print 不是格式化函數:只接受單一字串參數,返回 1,無格式化能力。速記卡:
sprintf = String Print Format → 回傳 Stringprintf = Print Format → Print (輸出)fprintf = File Print Format → 寫入 File/Stream