Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 147 · Strings in Depth

Formatting Strings

Format text in PHP with printf and sprintf - width, padding, precision and argument positions - plus number_format, str_pad tables, implode, explode and vsprintf.

Most programs end up turning values into text for a person to read: a price with two decimals, a report with neatly aligned columns, an invoice number padded with zeros, a list of tags joined by commas. You could build all of that with concatenation, but the result is fragile and hard to read. PHP gives you a small, precise toolkit for the job.

This lesson covers the format string language used by printf() and sprintf(), the friendlier number_format() for human-readable numbers, str_pad() for alignment, and implode()/explode() for turning arrays into strings and back. You met printf briefly in Output: echo, print, printf; here you'll learn every part of a format specification and the traps that catch people.

printf and sprintf

Both functions take a format string followed by values. Each % sequence in the format is a placeholder, filled in by the next value:

  • printf() prints the result and returns the number of bytes it printed.
  • sprintf() returns the result as a string and prints nothing.

You'll use sprintf() far more often, because you usually want to store, return or escape the text before it's shown.

PHP printf versus sprintf

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Three placeholders appear here. %s turns its value into a string, %.1f prints a float with one decimal (rounded, so 93.456 becomes 93.5), and %d prints an integer (the float is truncated to 93, not rounded). To print a literal percent sign, write %%. The last call shows that printf() returns 4: three characters plus the newline.

Anatomy of a format specification

Every placeholder follows the same pattern. Only the % and the final letter are required:

TEXT
%  [argnum$]  [flags]  [width]  [.precision]  specifier
Part Example Meaning
argnum$ %2$s Use the 2nd argument instead of the next one
flags -, +, 0, 'x, space Left-justify, always show the sign, pad with zeros, pad with the character x, pad with spaces (default)
width %8s Minimum number of characters; shorter results are padded
.precision %.2f, %.3s Decimals for floats, maximum length for strings
specifier d, s, f … How to interpret the value

The specifiers you'll actually use:

Specifier Output sprintf(…, 255)
%d Signed decimal integer 255
%u Unsigned integer (negative numbers wrap around) 255
%f / %F Float (%F ignores the locale, always uses .) 255.000000
%e / %E Scientific notation 2.550000e+2
%g / %G Shorter of %f and %e 255
%s String 255
%x / %X Hexadecimal, lower/upper case ff / FF
%o Octal 377
%b Binary 11111111
%c The byte with that code byte 255 (not valid text on its own)

Note that %f without a precision prints six decimals. You almost always want an explicit precision like %.2f.

Width, padding and alignment

The width is a minimum. If the value is shorter, PHP pads it, by default with spaces on the left, which right-aligns it. The - flag pads on the right instead. The 0 flag pads numbers with zeros, and a single quote followed by any character ('*, '.) chooses your own padding character.

PHP Width, flags and padding characters

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last line matters: a width never shortens a value. %3s with 'too long' prints all eight characters. If you need to cut text, use a precision.

Zero padding combined with - doesn't do what you might hope: sprintf('%-05d', 7) gives 7 with spaces, because padding on the right with zeros would change the number's value.

Precision for floats and strings

The precision after the dot has two meanings, depending on the specifier:

  • For f, F and e, it is the number of digits after the decimal point. The value is rounded.
  • For s, it is the maximum number of characters. Longer strings are cut off.
PHP Precision rounds floats and truncates strings

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last result surprises most people: 1.00, not 1.01. Floats are stored in binary, and 1.005 can't be represented exactly; the nearest double is a hair below it. Integers and Floats explains why. For money, store whole cents as integers (or use bcmath, covered in Math Functions) and format only at the very end.

Choosing arguments by position

Normally each placeholder takes the next argument. With %n$, you choose the argument by number, starting at 1. That lets you reuse a value or change the order without changing the argument list, which is exactly what translators need: word order differs between languages, but the code passes arguments in one fixed order.

PHP Numbered arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Don't mix numbered and unnumbered placeholders in one format string; it works, but it's very hard to read.

When arguments don't match

Since PHP 8.0, passing too few arguments throws an ArgumentCountError instead of quietly returning false. Extra arguments are ignored. Values are converted to the type the specifier asks for: %d with the string '12abc' prints 12, and %d with a float simply drops the fraction.

PHP
sprintf('%s and %s', 'tea');
// ArgumentCountError: 3 arguments are required, 2 given

The count in that message includes the format string itself, which is why it says 3 rather than 2.

Arrays of arguments: vsprintf and vprintf

When the values already live in an array, vsprintf() (returns) and vprintf() (prints) take the array as the second argument. Modern PHP can also unpack an array with ..., so sprintf($format, ...$values) does the same thing. Choose whichever reads better.

PHP Formatting rows from arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

number_format for human-readable numbers

printf is precise but knows nothing about thousands separators. For numbers people will read, use number_format():

PHP
number_format(float $num, int $decimals = 0, ?string $decimal_separator = '.', ?string $thousands_separator = ','): string

It rounds half away from zero, adds a thousands separator, and lets you choose both separators, which is how you produce European-style 1.234.567,89. Since PHP 8.3, $decimals may be negative to round to the left of the decimal point.

PHP number_format in action

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

number_format() returns a string, so do all arithmetic first and format last. A value like "1,234,567.89" is no longer a number PHP can calculate with.

Real localization (currency symbols, Indian digit grouping, right-to-left languages) is the job of the intl extension's NumberFormatter. It isn't installed on our runner, but you'll find it on most production servers.

Aligned tables with str_pad

str_pad($string, $length, $padWith = ' ', $type = STR_PAD_RIGHT) pads a string to a length, with STR_PAD_RIGHT, STR_PAD_LEFT or STR_PAD_BOTH (centered). Combined with printf widths, it's all you need for plain-text reports, CLI tools and log output.

PHP A plain-text report

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Byte widths and accented letters

str_pad() and the widths in printf count bytes, not characters. In UTF-8, é is two bytes, so café is five bytes long and a column containing it ends up one character short. Since PHP 8.3, mb_str_pad() counts characters instead:

PHP Bytes versus characters when padding

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The str_pad column is ragged; the mb_str_pad column lines up. Unicode and Multibyte Strings covers bytes and characters in depth. Wide characters such as Chinese or emoji still take two terminal columns each, which no padding function knows about.

Joining and splitting: implode and explode

implode($separator, $array) glues array values into one string. explode($separator, $string) cuts a string into an array at every separator. They are the bridge between lists in your code and lists in text: CSV-like lines, tags, paths, IDs in a query string.

PHP implode and explode

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Things to remember:

  • Empty fields are kept: 'red,green,,blue' produces an empty string at index 2. Filter them out with array_filter() if you don't want them (see array_map, array_filter and array_reduce).
  • explode(',', '') returns [''], an array with one empty string. Check for an empty input first if that matters.
  • An empty separator throws a ValueError. To split into characters, use str_split() or mb_str_split().
  • implode() converts values to strings: true becomes '1', while false and null become empty strings.
  • For real CSV data with quotes and embedded commas, use str_getcsv() and fgetcsv() (CSV Files). For splitting on a pattern, such as "any amount of whitespace", use preg_split() from Regular Expressions.

Formatting HTML safely

Formatting functions don't escape anything. If a value comes from a user and ends up in a web page, escape it with htmlspecialchars() after formatting, or escape each value before passing it in:

PHP
$html = sprintf(
    '<p class="price">%s costs %s</p>',
    htmlspecialchars($productName),
    number_format($price, 2),
);

The number needs no escaping because number_format() can only produce digits and the separators you chose. Preventing XSS explains the rules in full.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What does sprintf('%05.1f', 3.14159) return?

    The width 5 counts every character, including the dot. "3.1" is three characters, so two zeros are added in front.
  2. 2. What does sprintf('[%3s]', 'banana') return?

    A width is only a minimum, so longer values are never cut. Use a precision such as %.3s to truncate.
  3. 3. Which call prints "Paris is the capital of France" from the arguments 'France', 'Paris'?

    %2$s picks the second argument ('Paris') and %1$s the first ('France'), whatever order they were passed in.
  4. 4. What does explode(',', 'a,,b') return?

    Every separator splits the string, so the empty field between the two commas becomes an empty string.
  5. 5. What does number_format(2500.456, 2, ',', '.') return?

    The third argument is the decimal separator (a comma) and the fourth is the thousands separator (a dot). The value is rounded to 46.

Summary

  • printf() prints and returns a byte count; sprintf() returns the formatted string.
  • A placeholder is %[argnum$][flags][width][.precision]specifier, for example %-10s, %05d, %.2f, %2$s.
  • Width is a minimum and never cuts; precision rounds floats and truncates strings.
  • %% prints a percent sign; too few arguments throw ArgumentCountError in PHP 8.
  • vsprintf() and vprintf() take an array of values; sprintf($format, ...$array) works too.
  • number_format() adds thousands separators and returns a string, so format last.
  • str_pad() and printf widths count bytes; use mb_str_pad() (PHP 8.3) for accented text.
  • implode() joins arrays into strings and explode() splits them, keeping empty fields.

Next: Regular Expressions, where you'll match, extract and replace text by pattern instead of by fixed separators.