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: Duneprint 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.
Symptom
echo $stock;shows nothing on the page.
Drills
Answer fast — trust the rule.
Which output tool shows both the type and the value?
What does echo false; print?
How does print differ from echo?
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
falseandnullcompletely and cannot print an array.
