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:

Example 1Try it yourself
<?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

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:

Example 2Try it yourself
<?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:

Example 3Try it yourself
<?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?

  1. printf()
  2. sprintf()
  3. echo
  4. print_r()
Show answer

Answer: sprintf()