String Formatting (printf, sprintf)
Concatenating variables into a string with . works fine for a one-off message, but it falls apart once you need aligned columns, fixed decimal places, or zero-padded numbers. PHP borrows C's printf family of functions for exactly this job: you write a format string with placeholders, and PHP substitutes each placeholder with a formatted argument. This page covers printf(), sprintf(), vsprintf(), and the related number_format().
printf() vs sprintf(): print now or return later
Both functions accept the same format string and arguments. The difference is what they do with the result: printf() outputs it immediately (and returns the length printed), while sprintf() builds the formatted string and returns it without printing anything. In practice, sprintf() is the more commonly used of the two, since you usually want to store or further process the formatted text rather than print it on the spot.
printf-vs-sprintf.php
<?php
$name = 'Maya';
$score = 87;
printf("%s scored %d points\n", $name, $score);
$line = sprintf('%s scored %d points', $name, $score);
echo $line . PHP_EOL;Maya scored 87 points Maya scored 87 points
Common format specifiers
Every placeholder starts with % and ends with a conversion letter that says how to interpret the argument. %s treats it as a string, %d as a signed integer, and %f as a floating-point number (defaulting to six decimal places unless you say otherwise).
format-specifiers.php
<?php
printf("String: %s\n", 'PHP');
printf("Integer: %d\n", 42);
printf("Float: %f\n", 3.14159);String: PHP Integer: 42 Float: 3.141590
Width, padding, and precision
Between the % and the conversion letter you can insert width and precision modifiers. %05d pads an integer with leading zeros to a total width of five characters; %.2f rounds a float to exactly two decimal places, which is the standard way to print currency amounts.
width-precision.php
<?php
printf("Invoice #%05d\n", 42);
printf("Total: $%.2f\n", 19.9);
printf("Total: $%.2f\n", 19.999);Invoice #00042 Total: $19.90 Total: $20.00
vsprintf(): formatting with an array of arguments
vsprintf() behaves exactly like sprintf() except it takes its arguments as a single array instead of a variable-length argument list. It's the natural choice when the values to format already live in an array — for example, a row pulled from a database query — rather than as separate variables.
vsprintf-example.php
<?php
$row = ['Wireless Mouse', 2, 24.99];
echo vsprintf('%-20s qty:%d $%.2f', $row);Wireless Mouse qty:2 $24.99
That example also introduces the - flag and a width: %-20s left-aligns the string inside a 20-character field, padding with spaces on the right — the standard trick for lining up a text column before a numeric one.
number_format(): a friendlier alternative for numbers
When all you need is a nicely formatted number — thousands separators, a fixed number of decimals — number_format() is usually simpler than reaching for sprintf(). It takes the number, the decimal count, and optionally the decimal and thousands separator characters (useful for locales that swap the roles of . and ,).
number-format-example.php
<?php echo number_format(1234567.891) . PHP_EOL; // 1,234,568 echo number_format(1234567.891, 2) . PHP_EOL; // 1,234,567.89 echo number_format(1234567.891, 2, ',', '.'); // European style: 1.234.567,89
1,234,568 1,234,567.89 1.234.567,89
Building a formatted CLI report
Combining printf() with width and precision modifiers is the classic way to produce aligned, table-like output in a command-line script — no external library required.
cli-report.php
<?php
$items = [
['Keyboard', 2, 45.5],
['Monitor', 1, 189.99],
['USB Cable', 5, 3.25],
];
printf("%-12s %5s %10s\n", 'Item', 'Qty', 'Price');
foreach ($items as [$name, $qty, $price]) {
printf("%-12s %5d %10.2f\n", $name, $qty, $price);
}Item Qty Price Keyboard 2 45.50 Monitor 1 189.99 USB Cable 5 3.25
Specifier | Meaning |
|---|---|
%s | String |
%d | Signed integer |
%f | Floating-point number (default 6 decimals) |
%.2f | Floating-point rounded to 2 decimals |
%05d | Integer zero-padded to width 5 |
%-20s | String left-aligned in a 20-character field |
printf()prints immediately;sprintf()returns the formatted string for later use.%dfor integers,%f/%.Nffor floats,%sfor strings — the conversion letter must match the intended type.vsprintf()issprintf()for when your arguments already live in an array.number_format()is the simpler tool for thousands separators and fixed decimals on plain numbers.Width and
-alignment flags are what make CLI-style tabular output possible without extra libraries.