sprintf() — Format Strings in PHP
Also Known As
sprintf
printf
format string PHP
string formatting
TL;DR
sprintf() builds a string by substituting typed placeholders (%s, %d, %f, %05d) with values — safer and more expressive than string concatenation or interpolation for formatted output, especially for numbers, padding, and locale-independent formatting.
Explanation
sprintf() accepts a format string with conversion specifiers: %s (string), %d (integer), %f (float), %b (binary), %x (hex), %o (octal), %e (scientific notation). Each specifier can include a sign flag, padding character, alignment flag, width, and precision: '%-10s' left-aligns in a 10-character field; '%05d' zero-pads to 5 digits; '%.2f' rounds to 2 decimal places. Argument swapping ('%1$s has %2$d items') reorders values without rewriting the format string — useful for internationalisation. printf() is the print version; fprintf() writes to a file handle; vprintf() and vsprintf() accept an array of arguments.
Common Misconception
✗ sprintf() is slower than string concatenation so should be avoided. For a handful of values the difference is nanoseconds — not measurable in practice. The clarity and correctness benefits outweigh any micro-performance concern.
Why It Matters
String interpolation ('$total items') is fine for simple cases but breaks down for number formatting, padding, and locale-independent decimal points. sprintf('%.2f', $price) always produces '10.50' regardless of locale — correct for prices. '%05d' pads order numbers consistently. Argument swapping makes translated strings reorder values without code changes.
Common Mistakes
- Using sprintf() for SQL queries with user input — sprintf() does not escape values; use prepared statements with PDO or MySQLi for any SQL with external data.
- Forgetting that %s casts objects to string — if the object has no __toString(), this throws a fatal error in PHP 8.
- Using %.0f to format integers — it rounds floats, producing unexpected results near .5; use %d for integers.
- Not using argument swapping for translatable strings — position-dependent format strings require translators to rewrite the whole string to reorder arguments.
Code Examples
✗ Vulnerable
<?php
// ❌ Fragile manual formatting
$orderId = '00' . $id; // Only works for ids < 1000
$price = round($amount, 2); // 10.5 not 10.50 — missing trailing zero
$hex = dechex($color); // No padding — 'f' instead of '0f'
// Locale-dependent decimal separator
setlocale(LC_NUMERIC, 'de_DE');
$formatted = (string) 10.5; // '10,5' in German locale — breaks JSON
✓ Fixed
<?php
// ✅ sprintf() — explicit, locale-independent
$orderId = sprintf('%05d', $id); // '00042'
$price = sprintf('%.2f', $amount); // '10.50' always
$hex = sprintf('%02x', $color); // '0f' with padding
// Argument swapping for i18n
// English: 'Order #42 has 3 items'
// French: '3 articles dans la commande #42'
$msg = sprintf(__('Order #%1$d has %2$d items'), $orderId, $itemCount);
// Named argument equivalent in newer code
$sql = sprintf(
'SELECT * FROM %s WHERE id = %d LIMIT %d',
$table, $id, $limit
// Note: still use prepared statements for user input — not sprintf
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
23 Mar 2026
Views
20
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
No pings yesterday
Amazonbot 6
Perplexity 3
ChatGPT 2
Google 2
Meta AI 1
Ahrefs 1
Also referenced
How they use it
crawler 15
Related categories
⚡
DEV INTEL
Tools & Severity
⚙ Fix effort: Low
⚡ Quick Fix
Replace manual zero-padding like 'str_pad($n, 5, '0', STR_PAD_LEFT)' with sprintf('%05d', $n). Replace number_format() for simple decimal formatting with sprintf('%.2f', $amount).
📦 Applies To
PHP 4.0+
web
cli