vsprintf

Formats a string using values taken from an array instead of separate arguments.

Signature
vsprintf(string $format, array $values): string
  • Added in PHP 4.1.0

Parameters

ParameterTypeDescription
$formatstringThe format string, built from literal text and conversion specifications of the form %[argnum$][flags][width][.precision]specifier.
$valuesarrayThe values to substitute into the format string. They are consumed in array order; keys are ignored.

Return value

stringThe formatted string.

Errors

Throws a ValueError if the values array contains fewer items than the format string requires, or if a width or precision is negative or larger than PHP_INT_MAX.

Changelog

  • PHP 8.0.0No longer returns false on failure — a malformed format or a short values array now throws ValueError.
  • PHP 8.0.0An invalid [width] or [precision] throws ValueError instead of emitting E_WARNING.

vsprintf() does exactly what sprintf() does, except the substitution values arrive as one array rather than as a variable-length argument list. Everything you know about sprintf() format specifiers — padding, precision, %05.2f, positional %1$s — applies unchanged.

When to reach for it

Use it whenever the values are already in an array and you do not know how many there are at write time: a database row, a CSV line, the result of explode(), or a format string you assembled with str_repeat(). Without it you would need sprintf($format, ...$values) — which works fine on modern PHP and is the more common style today — but vsprintf() is clearer when the array is the natural unit and predates argument unpacking.

What trips people up

The array is read positionally. An associative array is accepted, but the keys are thrown away and the values are consumed in insertion order, so ['name' => 'Ana', 'age' => 30] and ['age' => 30, 'name' => 'Ana'] produce different output from the same format string.

Also remember that a literal percent sign in the format must be written %%, and that $ inside a double-quoted PHP string will interpolate — write positional formats like '%1$s' in single quotes.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Rendering a fixed-width report line from a database row without listing every column by hand.
  • Turning explode('-', $date) straight into a zero-padded ISO date string.
  • Formatting a message whose placeholder count is decided at runtime, using a format built with str_repeat().

Frequently asked questions

What is the difference between vsprintf and sprintf?

They format identically; only how you pass the values differs. sprintf() takes the values as separate arguments, while vsprintf() takes them as one array, which is easier when the values already live in an array or the count varies.

Does vsprintf still return false on error?

No. Since PHP 8.0 it throws a ValueError instead — for example when the array has fewer items than the format string needs. Wrap the call in try/catch if the values come from an untrusted source.

Can I use vsprintf with an associative array?

Yes, but the keys are ignored. Values are substituted in the order they appear in the array, so an associative array only works reliably if you control its insertion order.

More examples

Positional placeholders and reuse

The first call shows a positional specifier (%1$s) used twice from a two-item array — the same value is printed at the start and the end. The format string is single-quoted so PHP does not try to interpolate $s. The second call proves the PHP 8 behaviour change: a values array shorter than the format requires throws ValueError rather than returning false.

Example · php
<?php
$tpl = 'Hello %1$s, you have %2$d new messages. Bye, %1$s!';
echo vsprintf($tpl, ['Ana', 4]), "\n";

try {
    echo vsprintf('%s-%s', ['only-one']);
} catch (ValueError $e) {
    echo 'ValueError: ', $e->getMessage(), "\n";
}

A format string built at runtime

The number of columns is not known when the code is written, so the format string is generated with str_repeat() and fed the array directly. The first echo shows the raw format; the second shows each label left-padded to six characters and separated by pipes. Adding a fifth label needs no other change.

Example · php
<?php
$labels = ['CPU', 'RAM', 'Disk', 'Net'];
$format = str_repeat('%-6s|', count($labels)) . "\n";

echo $format;
echo vsprintf($format, $labels);

Associative arrays are read by position, not by key

Both arrays hold the same keys and values, but the second prints "92 scored 0" because vsprintf() ignores keys entirely and consumes values in insertion order. This is the single most common source of surprising output — if the array order is not guaranteed, sort it or list the values explicitly first.

Example · php
<?php
$a = ['name' => 'Ana', 'score' => 92];
$b = ['score' => 92, 'name' => 'Ana'];

echo vsprintf("%s scored %d\n", $a);
echo vsprintf("%s scored %d\n", $b);

Discussion

  • Be the first to comment on this lesson.