printf

Outputs a formatted string built from a format template and its arguments.

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

Parameters

ParameterTypeDescription
$formatstringThe format string. Conversion specifications follow the prototype %[argnum$][flags][width][.precision]specifier.
$valuesoptionalmixedVariadic. The values substituted into the format string, in order.

Return value

intThe length in bytes of the string that was output.

Errors

Throws ArgumentCountError when fewer arguments are supplied than the format requires, and ValueError when the argument count is zero or a width or precision is negative or larger than PHP_INT_MAX.

Changelog

  • PHP 8.0.0No longer returns false on failure.
  • PHP 8.0.0Throws ArgumentCountError when fewer arguments are given than the format string requires; previously an E_WARNING.
  • PHP 8.0.0Throws ValueError when the argument count is zero, or when width or precision is negative or greater than PHP_INT_MAX; previously an E_WARNING.

printf writes a formatted string straight to output. The format template is a normal string in which % introduces a conversion: %s for a string, %d for an integer, %f for a float, %X for uppercase hex, %b for binary, and %% for a literal percent sign.

Why not just concatenate?

Because of the modifiers between the % and the specifier. %.2f fixes decimal places, %10s right-aligns in a ten-character column, %-10s left-aligns, and %05d zero-pads. That is what makes printf the right tool for CLI tables, fixed-width report lines and log formats where columns must line up. It also keeps the sentence structure in one readable template instead of scattered across concatenation operators — handy when the template comes from a translation file.

Positional arguments

The %1$s form lets you refer to arguments by position, reuse one argument twice, or reorder them without touching the argument list. In a double-quoted PHP string the $ must be escaped as \$, or PHP will try to interpolate a variable.

Errors are now exceptions

Since PHP 8.0 a missing argument throws ArgumentCountError rather than printing a warning and continuing, so a mismatched template fails loudly instead of producing half a line.

Use sprintf when you want the string back instead of printed.

Example

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

When to use it

  • Print an aligned, fixed-width table of rows in a CLI script.
  • Format a monetary or percentage value to an exact number of decimal places in output.
  • Build a translatable message whose placeholders may appear in a different order per language.

Frequently asked questions

What is the difference between printf and sprintf?

printf writes the formatted text to output and returns its byte length; sprintf returns the formatted string and prints nothing. Use sprintf whenever you need to store, log or further process the result.

How do I print a literal percent sign with printf?

Double it: %% produces a single %. Writing a bare % before a letter is read as a conversion specification and will consume an argument.

Why does printf throw ArgumentCountError?

The format string contains more conversion specifications than you passed values. Since PHP 8.0 this is a thrown error instead of a warning, so count your placeholders — including any %% you meant as a literal.

More examples

An aligned CLI table

The header and the rows share one format string, so the columns line up exactly: names left-aligned in 10 characters, quantities right-aligned in 5, prices right-aligned in 12. number_format supplies the thousands comma, and %s is used for the price because it is already a string at that point.

Example · php
<?php
$rows = [['Widget', 4, 9.99], ['Gizmo', 12, 1249.5]];

printf("%-10s %5s %12s\n", 'Item', 'Qty', 'Price');
foreach ($rows as [$item, $qty, $price]) {
    printf("%-10s %5d %12s\n", $item, $qty, number_format($price, 2));
}

Positional and repeated arguments

Prints `30/08/2026`, `PHP is PHP`, `0.667` and `100% done`. The first line reverses the argument order without touching the array, the second reuses argument 1 twice, and the last shows %% escaping a literal percent sign. Note the backslashes before each $ — required inside a double-quoted PHP string.

Example · php
<?php
$date = ['2026', '08', '30'];
printf("%3\$s/%2\$s/%1\$s\n", ...$date);
printf("%1\$s is %1\$s\n", 'PHP');

echo sprintf('%.3f', 2 / 3), PHP_EOL;
printf("100%% done\n");

Discussion

  • Be the first to comment on this lesson.