Himanshu SharmaSoftware engineer
Let’s talk

PHP · Lesson 12 of 54

echo, print and printf

Print output in PHP with echo and print, format numbers and text with printf and sprintf, pad and align columns, and debug with print_r and var_dump.

12 minThe basicsUpdated 22 October 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonPrint and format output with echo, printf and sprintf, and pick the right debugging function.

echo

echo is the everyday way to send output. In a command-line script the output goes to the terminal; in a web page it becomes part of the HTML. echo accepts several values separated by commas:

php
<?php
$name = "Liam";
echo "Hello, ", $name, "!\n";
echo "Hello, " . $name . "!\n";
result
Hello, Liam!
Hello, Liam!

Both lines print the same thing. The comma form passes several values to echo; the dot form builds one string first. Either is fine.

echo is a language construct rather than a function, so brackets are optional and usually left out. In templates you will often see the short form <?= $name ?>, which means <?php echo $name; ?>; the Mixing PHP and HTML lesson uses it.

print

print is almost the same, with two differences: it takes exactly one value, and it returns 1, so it can be used inside an expression. In practice almost everyone uses echo.

php
<?php
print "Printed with print\n";
$result = print "";
var_dump($result);
result
Printed with print
int(1)

printf: formatted output

Joining numbers and text with dots gets messy when you need a fixed number of decimals or aligned columns. printf() takes a format string with placeholders, then the values to put in them:

php
<?php
$product = "Mechanical Keyboard";
$price = 89.5;
$quantity = 2;

printf("%s x %d = %.2f\n", $product, $quantity, $price * $quantity);
result
Mechanical Keyboard x 2 = 179.00

Each placeholder starts with % and ends with a letter that says how to show the value:

Placeholder Shows
%s a string
%d an integer (decimals are cut off)
%f a float, six decimals by default
%.2f a float with two decimals
%e scientific notation
%x an integer in hexadecimal
%% a literal percent sign
php
<?php
printf("%d%% off\n", 15);
printf("%f\n", 2.5);
printf("%.1f\n", 2.46);
printf("%x\n", 255);
printf("%d\n", 9.99);
result
15% off
2.500000
2.5
ff
9

%.1f rounds (2.46 becomes 2.5), while %d cuts off the decimals (9.99 becomes 9), just like an (int) cast.

Width, padding and alignment

A number between % and the letter sets a minimum width. Text is right-aligned by default; a minus sign left-aligns it; a zero pads numbers with zeros:

php
<?php
printf("[%8s]\n", "mug");
printf("[%-8s]\n", "mug");
printf("[%05d]\n", 42);
printf("[%8.2f]\n", 3.14159);
printf("Order #%06d\n", 1042);
result
[     mug]
[mug     ]
[00042]
[    3.14]
Order #001042

That makes simple text reports easy to line up:

php
<?php
$items = [
    ["Mechanical Keyboard", 1, 89.5],
    ["Ceramic Mug Set", 4, 18.75],
    ["Water Bottle", 2, 12],
];

foreach ($items as [$name, $qty, $price]) {
    printf("%-20s %3d %9.2f\n", $name, $qty, $qty * $price);
}
result
Mechanical Keyboard    1     89.50
Ceramic Mug Set        4     75.00
Water Bottle           2     24.00

sprintf: format without printing

sprintf() takes the same arguments as printf() but returns the string instead of printing it. Use it when you need the formatted value in a variable, a message or a database:

php
<?php
$invoice = sprintf("INV-%04d-%s", 7, "2026");
$label = sprintf("%.1f%% complete", 66.666);

echo $invoice . "\n";
echo $label . "\n";
result
INV-0007-2026
66.7% complete

Arguments can also be numbered, %1$s, so one value can be used twice or the order can change, which is useful for translated messages: sprintf('%2$s, %1$s', 'Asha', 'Verma') gives Verma, Asha.

Debugging output

Arrays and objects cannot be printed with echo. Three functions show them while you are developing:

php
<?php
$product = ["name" => "Yoga Mat", "price" => 24.99, "tags" => ["fitness"]];

print_r($product);
var_export($product);
echo "\n";
result
Array
(
    [name] => Yoga Mat
    [price] => 24.99
    [tags] => Array
        (
            [0] => fitness
        )

)
array (
  'name' => 'Yoga Mat',
  'price' => 24.99,
  'tags' =>
  array (
    0 => 'fitness',
  ),
)

print_r() is the most readable. var_dump() (from Data types and var_dump) adds types and string lengths, which is what you want when a value is mysteriously wrong. var_export() prints valid PHP code you could paste back into a file. In a browser, wrap debugging output in <pre> tags so the line breaks show. Remove it all before the code goes live.

Common mistakes

  • Trying to echo an array, which prints the word Array and a warning. Use print_r() or implode().
  • Mixing up printf and sprintf: $text = printf(...) prints immediately and stores the length.
  • Forgetting %% for a percent sign in a format string.
  • Using printf to show money without rounding rules in mind. %.2f rounds half away from zero, like round().

Exercise

Print a receipt line for each item below, with the name left-aligned in 18 characters, the quantity right-aligned in 3, and the line total with 2 decimals in 8. Then print the grand total in the same column. Items: Puzzle 1000 Pieces, 1 at 19.99; Resistance Bands, 3 at 14.99.

Show one possible answer
php
<?php
$items = [["Puzzle 1000 Pieces", 1, 19.99], ["Resistance Bands", 3, 14.99]];
$total = 0;

foreach ($items as [$name, $qty, $price]) {
    $line = $qty * $price;
    $total += $line;
    printf("%-18s %3d %8.2f\n", $name, $qty, $line);
}
printf("%-22s %8.2f\n", "Total", $total);
result
Puzzle 1000 Pieces   1    19.99
Resistance Bands     3    44.97
Total                     64.96

Key points

  • echo prints one or more values and is the usual choice. print prints one value and returns 1.
  • printf prints a formatted string; sprintf returns it instead of printing.
  • %s inserts text, %d an integer, %.2f a float with two decimals, %05d pads with zeros and %-10s left-aligns in 10 characters.
  • print_r and var_dump show arrays and objects for debugging; var_export prints valid PHP code.

Check yourself

1. What does printf('%.2f', 3.14159) print?
2. What is the difference between printf and sprintf?
3. What does sprintf('%05d', 42) return?
4. Which function prints an array in a readable form without type information?