{
    "slug": "php_sprintf_format",
    "term": "sprintf() — Format Strings in PHP",
    "category": "php",
    "difficulty": "beginner",
    "short": "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.",
    "long": "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.",
    "aliases": [
        "sprintf",
        "printf",
        "format string PHP",
        "string formatting"
    ],
    "tags": [
        "php-stdlib",
        "strings",
        "formatting",
        "i18n"
    ],
    "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."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "php_number_format",
        "string_functions",
        "php_mb_string",
        "prepared_statement"
    ],
    "prerequisites": [],
    "refs": [
        "https://www.php.net/sprintf",
        "https://www.php.net/printf"
    ],
    "bad_code": "<?php\n// ❌ Fragile manual formatting\n$orderId = '00' . $id; // Only works for ids < 1000\n$price = round($amount, 2); // 10.5 not 10.50 — missing trailing zero\n$hex = dechex($color); // No padding — 'f' instead of '0f'\n\n// Locale-dependent decimal separator\nsetlocale(LC_NUMERIC, 'de_DE');\n$formatted = (string) 10.5; // '10,5' in German locale — breaks JSON",
    "good_code": "<?php\n// ✅ sprintf() — explicit, locale-independent\n$orderId  = sprintf('%05d', $id);         // '00042'\n$price    = sprintf('%.2f', $amount);     // '10.50' always\n$hex      = sprintf('%02x', $color);      // '0f' with padding\n\n// Argument swapping for i18n\n// English: 'Order #42 has 3 items'\n// French:  '3 articles dans la commande #42'\n$msg = sprintf(__('Order #%1$d has %2$d items'), $orderId, $itemCount);\n\n// Named argument equivalent in newer code\n$sql = sprintf(\n    'SELECT * FROM %s WHERE id = %d LIMIT %d',\n    $table, $id, $limit\n    // Note: still use prepared statements for user input — not sprintf",
    "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).",
    "effort": "low",
    "created": "2026-03-23",
    "updated": "2026-03-23",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/php_sprintf_format",
        "html_url": "https://codeclaritylab.com/glossary/php_sprintf_format",
        "json_url": "https://codeclaritylab.com/glossary/php_sprintf_format.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[sprintf() — Format Strings in PHP](https://codeclaritylab.com/glossary/php_sprintf_format) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/php_sprintf_format"
            }
        }
    }
}