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
$name = "Liam";
echo "Hello, ", $name, "!\n";
echo "Hello, " . $name . "!\n";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 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
print "Printed with print\n";
$result = print "";
var_dump($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
$product = "Mechanical Keyboard";
$price = 89.5;
$quantity = 2;
printf("%s x %d = %.2f\n", $product, $quantity, $price * $quantity);Mechanical Keyboard x 2 = 179.00Each 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
printf("%d%% off\n", 15);
printf("%f\n", 2.5);
printf("%.1f\n", 2.46);
printf("%x\n", 255);
printf("%d\n", 9.99);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
printf("[%8s]\n", "mug");
printf("[%-8s]\n", "mug");
printf("[%05d]\n", 42);
printf("[%8.2f]\n", 3.14159);
printf("Order #%06d\n", 1042);[ mug]
[mug ]
[00042]
[ 3.14]
Order #001042That makes simple text reports easy to line up:
<?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);
}Mechanical Keyboard 1 89.50
Ceramic Mug Set 4 75.00
Water Bottle 2 24.00sprintf: 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
$invoice = sprintf("INV-%04d-%s", 7, "2026");
$label = sprintf("%.1f%% complete", 66.666);
echo $invoice . "\n";
echo $label . "\n";INV-0007-2026
66.7% completeArguments 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
$product = ["name" => "Yoga Mat", "price" => 24.99, "tags" => ["fitness"]];
print_r($product);
var_export($product);
echo "\n";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
Arrayand a warning. Useprint_r()orimplode(). - 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.
%.2frounds half away from zero, likeround().
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
$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);Puzzle 1000 Pieces 1 19.99
Resistance Bands 3 44.97
Total 64.96Key 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.