sprintf()
sprintf() — Return a formatted string.
Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
What it does
Returns a string produced according to the formatting string format.
Signature
sprintf(string $format, mixed ...$values): string
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| $format | string | An integer followed by a dollar sign $, to specify which number argument to treat in the conversion. |
| ...$values | mixed |
Return value
Returns a string produced according to the formatting string format.
Example
A runnable snippet:
$num = 5; $location = 'tree'; $format = 'There are %d monkeys in the %s'; echo sprintf($format, $num, $location);
Output:
There are 5 monkeys in the tree
Changelog
| Version | Change |
|---|---|
| 8.5.0 | A formatter that does not specify a precision now correctly treats it as a precision of 0, instead of incorrectly resetting the precision. |
| 8.0.0 | This function no longer returns false on failure. |
| 8.0.0 | Throws a ValueError if the number of arguments is zero; previously this function emitted an E_WARNING instead. |
| 8.0.0 | Throws a ValueError if [width] is less than zero or bigger than PHP_INT_MAX; previously this function emitted an E_WARNING instead. |
| 8.0.0 | Throws a ValueError if [precision] is less than zero or bigger than PHP_INT_MAX; previously this function emitted an E_WARNING instead. |
| 8.0.0 | Throws an ArgumentCountError when fewer arguments are given than required; previously this function emitted an E_WARNING instead. |
See also
printf(), fprintf(), vprintf(), vsprintf(), vfprintf(), sscanf(), fscanf(), number_format(), date()
All PHP 8.5 built-in functions
Reference card built from the PHP manual page sprintf() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.