sprintf

Returns a string built from a format template with values substituted into its placeholders.

Signature
sprintf(string $format, mixed ...$values): string
  • Added in PHP 4.0

Parameters

ParameterTypeDescription
$formatstringThe template, made of literal text and conversion specifications of the form %[argnum$][flags][width][.precision]specifier.
$valuesoptionalmixedVariadic list of values consumed by the conversion specifications, in order (unless argnum$ is used).

Return value

stringThe formatted string produced from format with values substituted into its conversion specifications.

Errors

Throws ArgumentCountError if fewer values are passed than the format consumes, and ValueError for an invalid width, precision, or specifier.

Changelog

  • PHP 8.0Throws ArgumentCountError when fewer values are supplied than the format requires; previously it emitted E_WARNING and returned false.
  • PHP 8.0Throws ValueError when no arguments are given, or when width or precision is negative or larger than PHP_INT_MAX; previously E_WARNING.
  • PHP 8.0The function no longer returns false on failure.

sprintf builds a string from a template instead of concatenating pieces. Each % specification pulls the next value off the argument list and renders it with a chosen type, width, padding and precision. It returns the result rather than printing it — use printf when you want output directly.

When to reach for it

Reach for it whenever a value needs a fixed shape: an invoice number padded to six digits with %06d, a money amount with exactly two decimals via %.2f, a hex colour with %02X, or a column-aligned report line with %-20s. It is also the clean way to keep a template in one place — a translation file, a constant — and fill it in later.

What trips people up

The escape character is %, not a backslash, so a literal percent sign is %%. Positional arguments start at 1, and inside double-quoted strings the $ in %1$s must be escaped as %1\$s or PHP tries to interpolate a variable. Since PHP 8.0 supplying too few values throws ArgumentCountError instead of quietly returning false. Width counts bytes, not characters, so alignment breaks on UTF-8 text.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Pad an order ID to a fixed width, e.g. INV-000042
  • Render a price with exactly two decimal places for an invoice line
  • Build an aligned plain-text table or CLI report
  • Convert RGB components into a #RRGGBB hex colour string

Frequently asked questions

What is the difference between sprintf and printf?

sprintf returns the formatted string, printf writes it straight to output and returns the number of bytes written. Use sprintf when you need to store, log or further process the result.

How do I print a literal percent sign with sprintf?

Write %% in the format string. The escape character is the percent sign itself, not a backslash, so "100%% done" produces "100% done".

Why does %1$s break inside a double-quoted string?

In double quotes PHP tries to interpolate $s as a variable. Escape it as %1\$s, or put the format in single quotes where no interpolation happens.

More examples

Flags, width and precision together

The output shows a fixed-width table: %-18s left-aligns the item name in 18 columns, and %'*9.2f right-aligns the price in 9 columns padded with asterisks instead of spaces (the ' flag sets a custom pad character). The last two lines show the same number rendered as binary, octal and scientific notation, and the + flag forcing an explicit sign on positive numbers.

Example · php
<?php
$rows = [['Coffee', 3.5], ['Tea', 12], ['Sparkling water', 1.25]];

foreach ($rows as [$item, $cost]) {
    echo sprintf("| %-18s | %'*9.2f |\n", $item, $cost);
}

echo sprintf("binary: %b  octal: %o  sci: %e\n", 42, 42, 1234.5);
echo sprintf("signed: %+d and %+d\n", 7, -7);

Reusing one value more than once

Positional specifications let a single value appear twice without passing it twice: %1$s refers to the first argument in both places. Because the template lives in a single-quoted string, the $ needs no escaping. The final line shows vsprintf consuming the same template with an array of arguments, which is what you want when the values arrive as a list.

Example · php
<?php
$template = '%1$s scored %2$d points. Well done, %1$s!';

echo sprintf($template, 'Ana', 31), "\n";
echo sprintf($template, 'Bruno', 8), "\n";

$args = ['Chen', 55];
echo vsprintf($template, $args), "\n";

What happens when arguments are missing

The format consumes two values but only one is supplied, so PHP 8 throws ArgumentCountError instead of returning false as PHP 7 did. The second line shows the escape rule: %% renders one literal percent sign, and the following %s still picks up its argument normally.

Example · php
<?php
try {
    echo sprintf('%s owes %d', 'Dana');
} catch (ArgumentCountError $e) {
    echo 'ArgumentCountError: ', $e->getMessage(), "\n";
}

echo sprintf('100%% done: %s', 'ok'), "\n";

Discussion

  • Be the first to comment on this lesson.