Skip to content
Tutorials Center
My learning

Topics

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
<?php
echo vsprintf("%04d-%02d-%02d", [2026, 3, 9]);
// 2026-03-09

Try it

PHP Values from an array

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.

PHP Runtime templates and errors

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

PHP
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 %name syntax; use strtr() 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) equals sprintf($f, ...$a). If the array has string keys, spreading would treat them as named arguments and fail, whereas vsprintf() 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 with vsprintf().
  • Escape for HTML before printing user data with vprintf(), as with any output.