Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 147 ยท Getting Started

Output: echo, print, printf

Learn every way to produce output in PHP - echo vs print, printf and sprintf formats, number_format, print_r, var_dump and var_export for debugging, and heredoc blocks.

Almost every PHP script produces output: an HTML page, a JSON response, a line in a terminal. PHP gives you several tools for it. echo and print send text. printf() and sprintf() format numbers and text precisely. And print_r(), var_dump() and var_export() show what's inside a variable, which you'll use constantly while debugging.

This lesson covers each one, when to choose it, and the differences that matter. By the end you'll know why echo is the everyday choice, how to print a price with exactly two decimals, and how to read the output of var_dump().

echo

echo is a language construct, not a function: it's built into PHP's grammar, so parentheses are optional and usually left out. It prints one or more values separated by commas:

PHP echo basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

echo adds nothing on its own: no spaces between the values, no newline at the end. That's why the examples end with PHP_EOL, a constant holding the line ending ("\n" on Linux and macOS). You can also write "\n" inside double quotes; both are common.

Commas and dots both work, with a subtle difference:

  • echo 'a', 'b'; prints two separate values.
  • echo 'a' . 'b'; first joins the strings into 'ab', then prints one value.

The result is the same text. Commas are slightly more efficient and avoid a precedence trap with arithmetic, so many developers prefer them when echoing several pieces.

print

print is the other output construct. It differs from echo in two small ways: it accepts exactly one value, and it returns 1, so it can be used inside an expression:

PHP print versus echo

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In practice, the return value of print is almost never useful. Most PHP code uses echo everywhere, and so does this tutorial. Recognize print when you see it, but don't worry about choosing it.

echo print
Values One or more, comma-separated Exactly one
Return value None (it's a statement) Always 1
Use in expressions No Yes
Parentheses Optional Optional

printf and sprintf: formatted output

When you need control over how numbers and text look, use printf(). It takes a format string with placeholders that start with %, followed by the values to put into them:

PHP printf placeholders

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is:

TEXT
Headphones cost 59.50 euros, 7 left.
00042
[     right]
[left      ]
87.3%

The most common placeholders:

Placeholder Meaning Example Result
%s String printf('%s', 'hi') hi
%d Integer (decimal) printf('%d', 7.9) 7
%f / %.2f Float / with 2 decimals printf('%.2f', 3.14159) 3.14
%05d Pad with zeros to width 5 printf('%05d', 42) 00042
%10s / %-10s Right / left align in width 10 printf('[%-4s]', 'ab') [ab ]
%x / %b Hexadecimal / binary printf('%x', 255) ff
%% A literal % printf('100%%') 100%

sprintf() works exactly like printf() but returns the formatted string instead of printing it. That's the one you'll use most, because you can store the result, return it from a function, or build HTML with it:

PHP sprintf returns a string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

%02d pads the seconds to two digits, so 247 seconds becomes 4:07 rather than 4:7. Formatting Strings covers every option of the format syntax, including argument numbering and vsprintf().

number_format: readable numbers

For displaying numbers to people, number_format() adds thousands separators and rounds to the decimals you choose. Its third and fourth arguments set the decimal point and thousands separator, so you can follow local conventions:

PHP number_format

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is:

TEXT
1,234,568
1,234,567.89
1.234.567,89
1 234 567.89

number_format() returns a string meant for display. Do calculations first and format at the very end; a formatted string like '1,234.57' is no longer a usable number. For money, also read the advice on exact arithmetic in Math Functions.

Inspecting values: print_r, var_dump, var_export

echo is for output meant for users. When you, the developer, want to see what's inside a variable, especially an array or object, use one of the three inspection functions. Each shows the same data with a different level of detail:

PHP print_r, var_dump and var_export

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

print_r: quick and readable

print_r() prints arrays and objects in a compact, human-friendly layout. It's great for a quick look, but it hides types: true prints as 1, false and null print as nothing, and you can't tell the number 312 from the string '312'.

Pass true as the second argument and print_r() returns the text instead of printing it, which is handy for logging: error_log(print_r($data, true));.

var_dump: types and all

var_dump() shows the type and value of everything, which makes it the most useful debugging tool of the three. Reading its output:

TEXT
array(5) {                       <- an array with 5 elements
  ["title"]=>
  string(16) "The Quiet Garden"  <- a string of 16 bytes
  ["pages"]=>
  int(312)                       <- an integer
  ["price"]=>
  float(18.5)                    <- a floating-point number
  ["inStock"]=>
  bool(true)                     <- a boolean
  ["tags"]=>
  array(2) {
    ...

The number in string(16) is the length in bytes, not characters. For text with accented letters or emoji the two differ, as Unicode and Multibyte Strings explains. var_dump() accepts several values at once (var_dump($a, $b);) and always prints; it has no "return" mode.

var_export: valid PHP code

var_export() prints the value as PHP source code you could paste back into a script. Strings get quotes, true stays true, and null shows as NULL. Like print_r(), it returns the text instead when you pass true as the second argument. It's used to generate configuration files and cached data.

Here's how the three treat the "invisible" values:

PHP How each shows true, false and null

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

print_r() shows [1] [] [] [0] [0] []: you can't tell false from null or 0 from '0'. var_export() and var_dump() make every value unambiguous. When a bug involves types, reach for var_dump().

Tip: Wrap debugging output in <pre> tags when you view it in a browser, so the line breaks and indentation survive: echo '<pre>'; var_dump($data); echo '</pre>';. And remove debug output before your code goes live; Debugging PHP shows better tools for bigger problems.

Heredoc: printing blocks of text

For several lines of text with variables in them, a heredoc is easier to read than many echo statements. It starts with <<< and an identifier of your choice, and ends with the same identifier on its own line. Variables are interpolated just like in double-quoted strings:

PHP Heredoc output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Since PHP 7.3, the closing identifier may be indented, and PHP removes that same amount of indentation from every line. That's why the output starts at the left margin even though the text is indented in the code. A heredoc can't call functions directly inside the text, so the example formats the total into a variable first. Heredoc and its literal twin, nowdoc, are covered fully in Strings.

Choosing the right tool

You want to... Use
Print text or HTML for users echo
Format numbers or align columns printf(), or sprintf() to get a string
Show a number with thousands separators number_format()
Quickly look inside an array print_r()
See exact types while debugging var_dump()
Turn data into PHP code var_export()
Output several lines with variables A heredoc with echo

And one rule from the web chapters: whenever you print data into an HTML page, escape it with htmlspecialchars() first. It's the topic of Preventing XSS.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does echo 'a', 'b', 'c'; print?

    echo accepts several values and prints them one after another with nothing in between.
  2. 2. What does printf('%05.1f', 3.14159); print?

    .1f rounds to one decimal (3.1), and 05 pads the whole result to five characters with zeros: 003.1.
  3. 3. What is the difference between printf() and sprintf()?

    Both use the same format syntax. sprintf() returns the formatted text so you can store or return it.
  4. 4. Which call makes it clear that a value is false and not null?

    var_dump() prints bool(false) or NULL. print_r(), echo and print show nothing for both.
  5. 5. What does print 'x' return?

    print always returns 1, which is why it can be used inside an expression. echo returns nothing.

Summary

  • echo prints one or more comma-separated values and adds no spaces or newlines; it's the everyday output tool. print takes one value and returns 1.
  • printf() prints formatted text with placeholders like %s, %d, %.2f and %05d; sprintf() returns it instead.
  • number_format() produces display strings with thousands separators and a chosen number of decimals.
  • For debugging: print_r() is compact, var_dump() shows exact types and sizes, var_export() prints valid PHP code. print_r() and var_export() return a string when given true as the second argument.
  • Heredoc blocks print multi-line text with variables, and an indented closing marker removes the indentation.

Next: Variables, where you'll learn the rules for naming, assigning and checking variables.