Skip to content

PHP Tutorial Strings

Formatting Strings

Lesson 69 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

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.
index.php
PHP
<?php
$name = "Anil";
$items = 3;
$total = 1499.5;

echo sprintf("%s bought %d items for %.2f", $name, $items, $total);
Output
OUTPUT
Anil bought 3 items for 1499.50

The format string has placeholders, and PHP fills them from the following arguments, in order.

Common placeholders

PlaceholderMeaning
%sString
%dInteger
%fFloat
%.2fFloat with 2 decimals
%05dInteger padded with zeros to width 5
%10sString right-aligned in 10 spaces
%-10sString left-aligned in 10 spaces
%xHexadecimal
%bBinary
%%A literal percent sign
index.php
PHP
<?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);
Output
OUTPUT
00042
[     right]
[left      ]
1010
ff
Discount: 20%

A neat table

index.php
PHP
<?php
$rows = [["Pen", 12.5], ["Notebook", 80], ["Bag", 799.99]];

foreach ($rows as [$item, $price]) {
    printf("%-10s %8.2f\n", $item, $price);
}
Output
OUTPUT
Pen           12.50
Notebook      80.00
Bag          799.99

Repeat a value with numbered placeholders

index.php
PHP
<?php
printf("%1\$s likes %2\$s. %1\$s also likes %3\$s.", "Mira", "tea", "books");
Output
OUTPUT
Mira likes tea. Mira also likes books.

number_format(): thousands separators

index.php
PHP
<?php
echo number_format(1234567.891) . "\n";
echo number_format(1234567.891, 2) . "\n";
echo number_format(1234567.891, 2, ",", ".");
Output
OUTPUT
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.

index.php
PHP
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);
lightbulb
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.