Skip to the workspace
Pebellslearn by building
Output and Arrays  ›  Lesson

Printing Values: echo, print, var_dump, print_r

var_dump 12 minecho and print send text to the visitor, while var_dump shows a value's type and contents and print_r shows an array's structure for debugging.

php / Printing Values: echo, print, var_dump, print_r

Explore each scene at your own pace.

01 · The rule

The rule

Printing Values: echo, print, var_dump, print_r

echo and print send text to the visitor, while var_dump shows a value's type and contents and print_r shows an array's structure for debugging.

Choose user-facing output or diagnostic inspection according to the information needed.

A Pageturn page shows a blank space where the stock count should be. Is the value 0, false, null, or an empty string? echo cannot tell you, because all four can print the same way. PHP gives you four ways to output a value, and choosing the right one is half of debugging.

The rule

echo and print are for visitors; var_dump and print_r are for you.

echo writes text to the output. It is a language construct, so parentheses are optional, and it accepts several values separated by commas:

<?php
$title = "Dune";
$stock = 3;
echo "Title: ", $title, "\n";   // Title: Dune

print does the same job but takes exactly one value and returns 1, so it can appear inside an expression. In everyday code it is simply the slower-to-type cousin of echo.

var_dump shows the type and the value, and it handles arrays and nested data:

var_dump($stock, false, null, 7.50);
// int(3)
// bool(false)
// NULL
// float(7.5)

print_r prints arrays in a readable, indented layout, but without types:

print_r(["Dune", "Emma"]);
// Array
// (
//     [0] => Dune
//     [1] => Emma
// )

Pass true as a second argument, as in print_r($books, true), and it returns the text instead of printing it, which is handy for writing to a log.

Two traps hide here. echo false and echo null print nothing at all, while echo true prints 1. And echo on an array prints the word Array along with a warning, because an array has no single piece of text to show.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.