Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

Printing Values: echo, print, var_dump, print_r

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.

The shortcut

Pick by who is reading and what you need to know:

  • A visitor reading the page → echo.
  • You, checking the exact type of something → var_dump.
  • You, scanning the shape of an array → print_r.
The mystery blank stock countStep 1 of 4
  1. Symptom

    echo $stock; shows nothing on the page.

Drills

Answer fast — trust the rule.

quick drill

Which output tool shows both the type and the value?

quick drill

What does echo false; print?

quick drill

How does print differ from echo?

quick drill

You want an array's readable layout stored in $log instead of printed. What do you write?

Remember

  • echo and print are for visitors; var_dump and print_r are for you.
  • Shortcut: need the type → var_dump; need an array's shape → print_r.
  • Trap: echo hides false and null completely and cannot print an array.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainWhich output tool?

A stock count shows as blank on a Pageturn page. Explain why echo cannot tell you what is wrong, which tool you would use instead, and what the different possible results would mean.