echo:
- Outputs one or more strings separated by commas
- No return valuee.g.
echo "String 1", "String 2"
print :
- Outputs only a single string
- Returns
1
, so it can be used in an expressione.g.print "Hello"
or,if ($expr && print "foo")
print_r() :
- Outputs a human-readable representation of any one value
- Accepts not just strings but other types including arrays and objects, formatting them to be readable
- Useful when debugging
- May return its output as a return value (instead of echoing) if the second optional argument is given
var_dump() :
- Outputs a human-readable representation of one or more values separated by commas
- Accepts not just strings but other types including arrays and objects, formatting them to be readable
- Uses a different output format to
print_r()
, for example it also prints the type of values - Useful when debugging
- No return value
Notes:
- Even though
print
can be used in an expression, I’d generally avoid doing so for the sake of readability (and because it’s unlikely to ever be useful). The precedence rules when it interacts with other operators can also be confusing. - Whereas
echo
andprint
are language constructs,print_r()
andvar_dump()
are regular functions. You don’t need parentheses to enclose the arguments toecho
orprint
(and if you do use them, they’ll be treated as they would in an expression).