PHP 8 reference · String Functions
PHP sprintf() Function
Return a formatted string built from a template with placeholders like %s, %d and %.2f. Format numbers, pad and align.
PHP 8 Since 4.0
Syntax
sprintf(string $format, mixed ...$values): string
Parameters
| Parameter | Description |
|---|---|
format |
The template: %s string, %d integer, %.2f decimal, %05d zero-padded, %-10s left-aligned, %% a percent sign. |
values |
The values for the placeholders, in order. |
Return value
The formatted string.
Examples
<?php
echo sprintf("%s is %d years old", "Ada", 36), "\n";
echo sprintf("Total: %.2f", 19.5), "\n";
echo sprintf("Invoice #%05d", 42), "\n";
Output
Ada is 36 years old Total: 19.50 Invoice #00042
<?php
foreach (["Tea" => 3.5, "Carrot cake" => 12.25] as $item => $price) {
echo sprintf("%-12s%8.2f", $item, $price), "\n";
}
Output
Tea 3.50 Carrot cake 12.25
<?php
echo sprintf('%2$s, %1$s', "Ada", "Lovelace"), "\n";
echo sprintf("%b %o %X %e", 10, 8, 255, 1234.5), "\n";
Output
Lovelace, Ada 1010 10 FF 1.234500e+3
Version history
In other languages
str.format()· Pythonformat()· Python
Related
printf()· Output a formatted string, using the same placeholders as sprintf(), and return the number of bytes printed.vsprintf()· Format a string like sprintf(), but take the values from an array. Useful when the number of values varies.number_format()· Format a number with grouped thousands and a fixed number of decimals, such as 1,234,567.89 or 1.234,57.str_pad()· Pad a string to a given length with spaces or another string, on the right, left or both sides.- PHP Strings · tutorial
- PHP echo and print · tutorial