Wednesday, October 28, 2015

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

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

var_dump($values);
print_r ($values);
With print_r you can't tell the difference between 0 and 0.0, or false and '':
array(4) {
  [0]=>
  int(0)
  [1]=>
  float(0)
  [2]=>
  bool(false)
  [3]=>
  string(0) ""
}

Array
(
    [0] => 0
    [1] => 0
    [2] => 
    [3] => 
)


echo
  • Outputs one or more strings separated by commas
  • No return value
    e.g. echo "String 1", "String 2"

    1. echo is a statement i.e used to display the output. it can be used with parentheses echo or without parentheses echo.
    2. echo can pass multiple string separated as ( , )
    3. echo doesn’t return any value
    4. echo is faster then print
print
  • Outputs only a single string
  • Returns 1, so it can be used in an expression
    e.g. print "Hello"
    or, if ($expr && print "foo")
    1. Print is also a statement i.e used to display the output. it can be used with parentheses print( ) or without parentheses print.
    2. using print can doesn’t pass multiple argument
    3. print always return 1
    4. it is slower than echo
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
var_export()
  • Outputs a human-readable and PHP-executable representation of any one value
  • Accepts not just strings but other types including arrays and objects, formatting them to be readable
  • Uses a different output format to both print_r() and var_dump() - resulting output is valid PHP code!
  • Useful when debugging
  • May return its output as a return value (instead of echoing) if the second optional argument is given
Notes:
  • Even though print can be used in an expression, I recommend people avoid doing so, because it is bad for code readability (and because it's unlikely to ever be useful). The precedence rules when it interacts with other operators can also be confusing. Because of this, I personally don't ever have a reason to use it over echo.
  • Whereas echo and print are language constructs, print_r() and var_dump()/var_export() are regular functions. You don't need parentheses to enclose the arguments to echo or print (and if you do use them, they'll be treated as they would in an expression).

No comments:

Post a Comment