Strings7 min readExamples run on PHP 8.5.10

vsprintf()

Learn how PHP 8.4 vsprintf() builds a formatted string from a format and an array, with padding, positional arguments, errors and common mistakes.

Signature

vsprintf(string $format, array $values): string
Available since PHP 4.1.07.48.08.18.28.38.48.5All versions →

Purpose

vsprintf() does the same job as sprintf(), but the values to insert arrive as one array instead of a list of separate arguments. It is useful when the values are already collected in an array, for example after explode(), from a database-style row, or from a function that returns a list. It returns the finished string and never prints anything.

Signature

Parameters and defaults

  • $format: a string made of ordinary characters, which are copied as they are, and conversion specifications, which each consume a value. Neither parameter has a default value.
  • $values: the array whose values feed the conversion specifications.

A conversion specification has the shape %[argnum$][flags][width][.precision]specifier.

  • argnum$ picks a value by its position, starting at 1, such as %2$s.
  • Flags include - for left-justify, + to show a plus sign on positive numbers, 0 for zero padding, and 'x to pad with any character x.
  • width is the minimum length of the converted text.
  • .precision sets the digits after the decimal point for f, F, e and E, and cuts off the text for s.
  • Common specifiers are s (string), d (signed integer), u (unsigned), f and F (float), x and X (hex), o (octal), b (binary), c (character from a code) and % (a literal percent sign that needs no value).

The function coerces each value to the type the specifier expects, so %d turns a numeric string into an integer.

Return value and failure cases

The return value is always a string. Since PHP 8.0.0 the function no longer returns false. Problems throw a ValueError, which happens when:

  • fewer values are supplied than the format needs,
  • a width or precision is negative or larger than PHP_INT_MAX,
  • the number of arguments is zero.

Extra values that the format never uses are ignored without an error.

Example 1: zero-padded parts

The classic use is to rebuild a date from pieces. %04d pads to four digits, %02d to two.

Example
<?php
$parts = explode('-', '1988-8-1');
echo vsprintf("%04d-%02d-%02d", $parts), "\n";
Output
1988-08-01

Example 2: positional arguments and alignment

With argnum$ you can use values in any order or more than once. Here -10 left-justifies the name in ten characters, 3 right-aligns the quantity, and 8.2 gives a width of eight with two decimals.

Example
<?php
$row = ['Widget', 4, 3.5];
echo vsprintf('%1$-10s|%2$3d|%3$8.2f|', $row), "\n";
Output
Widget    |  4|    3.50|

Single quotes matter here: in a double-quoted string PHP would try to interpolate $-10s or $3d and you would need to escape every dollar sign.

Example 3: too few values

Because the failure is an exception, you can catch it. This example prints only the class name, so it does not depend on the wording of the message.

Example
<?php
try {
    echo vsprintf('%s and %s', ['only one']);
} catch (ValueError $e) {
    echo get_class($e), "\n";
}
Output
ValueError

Edge cases

  • The array is consumed by the order of its values. Keys are not used as names, so build the array in the order the format expects, or use argnum$ to choose positions.
  • %% prints a literal percent sign and does not use up a value.
  • The c specifier ignores width and padding.
  • Width and precision on s count bytes, so multibyte text such as UTF-8 may be padded or cut in the middle of a character. Use multibyte-aware functions when that matters.
  • f depends on the current locale for the decimal separator, while F does not. Prefer F when the output must be stable, for instance in data files.
  • A precision written as a bare period, such as %.f, means a precision of 0.

Common mistakes

  1. Passing separate arguments. vsprintf('%d %d', 1, 2) is a mistake because the second parameter must be an array. Use sprintf() for separate arguments.
  2. Counting values wrongly. Mixing numbered and unnumbered specifiers makes it easy to ask for more values than you supplied, which throws a ValueError.
  3. Using a double-quoted format with $. Positional formats such as %1$s belong in single quotes, or the dollar sign has to be escaped.
  4. Expecting echo. The function returns a string. Use vprintf() if you want output written directly.
  5. Assuming rounding is a currency solution. %.2f rounds a float for display, but it does not make floating-point money arithmetic exact.
  • sprintf() for separate arguments
  • vprintf() to print the result
  • printf() and fprintf() for printing or writing to a stream
  • vfprintf() for the array form with streams
  • number_format() for grouped thousands
  • sscanf() for parsing text with a similar format syntax

Recap

vsprintf() takes a format string and an array and returns the formatted result as a string. Learn the pattern %[argnum$][flags][width][.precision]specifier, supply enough values, prefer single-quoted formats when using positions, and remember that failures throw a ValueError in PHP 8.

Tested examples

Zero-padded date parts
<?php
$parts = explode('-', '1988-8-1');
echo vsprintf("%04d-%02d-%02d", $parts), "\n";
Output
1988-08-01
Positional arguments and alignment
<?php
$row = ['Widget', 4, 3.5];
echo vsprintf('%1$-10s|%2$3d|%3$8.2f|', $row), "\n";
Output
Widget    |  4|    3.50|
Catching a ValueError for missing values
<?php
try {
    echo vsprintf('%s and %s', ['only one']);
} catch (ValueError $e) {
    echo get_class($e), "\n";
}
Output
ValueError