PHP Tutorial · PHP Basics · Lesson 6 of 38
PHP echo and print
Output text with echo, print, printf and string interpolation.
echo
echo outputs one or more strings. It's the most common way to output in PHP:
<?php
$lang = "PHP";
echo "Hello ", "World", "\n";
echo "I am learning $lang\n";
echo "Braces help: {$lang}8\n";
print "print works too\n";
Output
Hello World I am learning PHP Braces help: PHP8 print works too
print works like echo but takes one argument and returns 1. In practice, use echo.
printf and sprintf
printf() formats and prints; sprintf() formats and returns a string. Placeholders: %s string, %d integer, %.2f float with 2 decimals, %05d zero-padded:
<?php
$item = "Coffee";
$price = 3.5;
$qty = 2;
printf("%s x %d = $%.2f\n", $item, $qty, $price * $qty);
$code = sprintf("ORD-%05d", 42);
echo $code, "\n";
Output
Coffee x 2 = $7.00 ORD-00042
Debug output
print_r() and var_dump() show the structure of arrays and objects — var_dump also shows types:
<?php
$user = ["name" => "Ada", "age" => 36, "admin" => false];
print_r($user);
var_dump($user["age"], $user["admin"]);
Output
Array
(
[name] => Ada
[age] => 36
[admin] =>
)
int(36)
bool(false)Test yourself
Which function formats a string and returns it without printing?
printf()sprintf()echoprint_r()
Show answer
Answer: sprintf()