Back to results for “Date”
PHP › Strings & String Functions

How does the sprintf function let you build formatted strings with precise control over things like decimal places, padding, and alignment?

Intermediate

Answer

The sprintf function builds a formatted string based on a template containing special placeholders, each describing exactly how a corresponding value should be inserted and formatted, letting you control details such as how many decimal places a floating point number should display, whether a number should be padded with leading zeros to reach a fixed width, or whether text should be left or right aligned within a fixed width field, which is especially useful for generating consistently formatted output such as invoices, reports, or aligned tabular data.
$price = 9.5;
echo sprintf('Price: $%.2f', $price);  // Outputs: Price: $9.50

$id = 7;
echo sprintf('Order #%04d', $id);     // Outputs: Order #0007
Real-world example An invoice generation script uses sprintf to ensure every displayed price consistently shows exactly two decimal places, regardless of whether the underlying stored value happens to be a whole number or has more decimal precision.

Common follow-ups: What is the difference between sprintf and printf?;What other formatting placeholders are available for things like padding characters or string alignment?