What's the difference between echo, print, and print_r in PHP?



I use echo and print_r much, and almost never use print.

I feel echo is a macro, and print_r is an alias of var_dump.

But that's not the standard way to explain the differences.

2/2/2015 11:37:31 AM

print and echo are more or less the same; they are both language constructs that display strings. The differences are subtle: print has a return value of 1 so it can be used in expressions whereas echo has a void return type; echo can take multiple parameters, although such usage is rare; echo is slightly faster than print. (Personally, I always use echo, never print.)

var_dump prints out a detailed dump of a variable, including its type and the type of any sub-items (if it's an array or an object). print_r prints a variable in a more human-readable form: strings are not quoted, type information is omitted, array sizes aren't given, etc.

var_dump is usually more useful than print_r when debugging, in my experience. It's particularly useful when you don't know exactly what values/types you have in your variables. Consider this test program:

$values = array(0, 0.0, false, '');

print_r ($values);

With print_r you can't tell the difference between 0 and 0.0, or false and '':

array(4) {
  string(0) ""

    [0] => 0
    [1] => 0
    [2] => 
    [3] => 
5/14/2013 8:42:56 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow