When a sentence needs several values and exact number formatting, sprintf() is cleaner than joining with dots.
sprintf()returns the formatted string.printf()prints it.
<?php
$name = "Anil";
$items = 3;
$total = 1499.5;
echo sprintf("%s bought %d items for %.2f", $name, $items, $total);
Anil bought 3 items for 1499.50
The format string has placeholders, and PHP fills them from the following arguments, in order.
Common placeholders
| Placeholder | Meaning |
|---|---|
%s | String |
%d | Integer |
%f | Float |
%.2f | Float with 2 decimals |
%05d | Integer padded with zeros to width 5 |
%10s | String right-aligned in 10 spaces |
%-10s | String left-aligned in 10 spaces |
%x | Hexadecimal |
%b | Binary |
%% | A literal percent sign |
<?php
printf("%05d\n", 42);
printf("[%10s]\n", "right");
printf("[%-10s]\n", "left");
printf("%b\n", 10);
printf("%x\n", 255);
printf("Discount: %d%%", 20);
00042
[ right]
[left ]
1010
ff
Discount: 20%
A neat table
<?php
$rows = [["Pen", 12.5], ["Notebook", 80], ["Bag", 799.99]];
foreach ($rows as [$item, $price]) {
printf("%-10s %8.2f\n", $item, $price);
}
Pen 12.50
Notebook 80.00
Bag 799.99
Repeat a value with numbered placeholders
<?php
printf("%1\$s likes %2\$s. %1\$s also likes %3\$s.", "Mira", "tea", "books");
Mira likes tea. Mira also likes books.
number_format(): thousands separators
<?php
echo number_format(1234567.891) . "\n";
echo number_format(1234567.891, 2) . "\n";
echo number_format(1234567.891, 2, ",", ".");
1,234,568
1,234,567.89
1.234.567,89
Why not just echo?
Compare these two lines. The second shows the final text at a glance.
echo "Hello " . $name . ", you owe " . number_format($amount, 2) . " by " . $date . ".";
echo sprintf("Hello %s, you owe %s by %s.", $name, number_format($amount, 2), $date);
Money formatting
number_format() is for display only. Do your maths on plain numbers (or integer cents) and format at the end. See Number Formatting.