PHP Reference ยท String Functions
PHP vsprintf() and vprintf() functions
Reference for PHP vsprintf() and vprintf(): format a string with the values taken from an array, how keys are ignored, and the errors for too few values.
vsprintf() and vprintf() are the array versions of sprintf() and printf(). Instead of passing each value as its own argument, you pass one array. The first element fills the first placeholder, the second element the second, and so on. vsprintf() returns the string, vprintf() prints it and returns its length.
They are useful when the number of values is decided at runtime, or when the values already live in an array, for example a database row or a translated message template.
<?php echo vsprintf("%04d-%02d-%02d", [2026, 3, 9]); // 2026-03-09
Try it
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.
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.
Syntax
vsprintf(string $format, array $values): string vprintf(string $format, array $values): int
| Name | Description |
|---|---|
$format |
The template, using the same placeholders as sprintf(). |
$values |
An array of values. Keys are ignored; the array is read in order. |
Return value: vsprintf() returns the formatted string; vprintf() returns the number of bytes it printed.
Errors: a ValueError if the array has fewer elements than the format needs, or for an unknown specifier. Note this differs from sprintf(), which throws ArgumentCountError for the same mistake.
Usage notes
- Keys do not name placeholders. There is no
%namesyntax; usestrtr()or a small helper if you want named placeholders. - Too many values are fine, too few are not. Surplus elements are ignored silently.
- Same as
sprintf()with spread. For a list,vsprintf($f, $a)equalssprintf($f, ...$a). If the array has string keys, spreading would treat them as named arguments and fail, whereasvsprintf()just ignores the keys. - Translated text. Different languages may need a different word order, so keep messages as templates with
n$placeholders and format them withvsprintf(). - Escape for HTML before printing user data with
vprintf(), as with any output.