Signature
vsprintf(string $format, array $values): stringPurpose
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,0for zero padding, and'xto pad with any characterx. widthis the minimum length of the converted text..precisionsets the digits after the decimal point forf,F,eandE, and cuts off the text fors.- Common specifiers are
s(string),d(signed integer),u(unsigned),fandF(float),xandX(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.
$parts = explode('-', '1988-8-1');
echo vsprintf("%04d-%02d-%02d", $parts), "\n";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.
$row = ['Widget', 4, 3.5];
echo vsprintf('%1$-10s|%2$3d|%3$8.2f|', $row), "\n";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.
try {
echo vsprintf('%s and %s', ['only one']);
} catch (ValueError $e) {
echo get_class($e), "\n";
}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
cspecifier ignores width and padding. - Width and precision on
scount 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. fdepends on the current locale for the decimal separator, whileFdoes not. PreferFwhen 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
- Passing separate arguments.
vsprintf('%d %d', 1, 2)is a mistake because the second parameter must be an array. Usesprintf()for separate arguments. - Counting values wrongly. Mixing numbered and unnumbered specifiers makes it easy to ask for more values than you supplied, which throws a
ValueError. - Using a double-quoted format with
$. Positional formats such as%1$sbelong in single quotes, or the dollar sign has to be escaped. - Expecting echo. The function returns a string. Use
vprintf()if you want output written directly. - Assuming rounding is a currency solution.
%.2frounds a float for display, but it does not make floating-point money arithmetic exact.
Related functions
sprintf()for separate argumentsvprintf()to print the resultprintf()andfprintf()for printing or writing to a streamvfprintf()for the array form with streamsnumber_format()for grouped thousandssscanf()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
$parts = explode('-', '1988-8-1');
echo vsprintf("%04d-%02d-%02d", $parts), "\n";
1988-08-01
$row = ['Widget', 4, 3.5];
echo vsprintf('%1$-10s|%2$3d|%3$8.2f|', $row), "\n";
Widget | 4| 3.50|
try {
echo vsprintf('%s and %s', ['only one']);
} catch (ValueError $e) {
echo get_class($e), "\n";
}
ValueError