"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > What's the Difference Between `echo`, `print`, `print_r`, and `var_dump` in PHP?

What's the Difference Between `echo`, `print`, `print_r`, and `var_dump` in PHP?

Published on 2024-12-23
Browse:511

What's the Difference Between `echo`, `print`, `print_r`, and `var_dump` in PHP?

Distinguishing between Echo, Print, Print_r, and Var_dump in PHP

Many PHP developers frequently utilize echo and print_r for outputting data. However, print, surprisingly, is rarely used. Despite their apparent similarities, these language constructs have distinct characteristics.

Echo vs. Print

Both echo and print primarily serve the purpose of displaying strings. However, there are some subtle differences between them:

  • Print has a return value of 1, enabling its inclusion in expressions, while echo has a void return type.
  • Echo allows multiple parameters, but this practice is uncommon.
  • Echo marginally outperforms print in terms of speed.

As a general rule, echo is commonly preferred over print.

Var_dump vs. Print_r

Var_dump presents a comprehensive breakdown of a variable, including its type and sub-items (for arrays or objects). In contrast, print_r displays variables in a more user-friendly manner, omitting type information and simplifying array representation.

Var_dump generally proves more valuable during debugging, especially when dealing with unfamiliar variable types and values. For instance, consider the example:

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

var_dump($values);
print_r ($values);

Print_r fails to differentiate 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] => 
)
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3