我经常使用echo和print_r,几乎从不使用print。

我觉得echo是一个宏,而print_r是var_dump的别名。

但这不是解释差异的标准方式。


当前回答

只是为了补充John的回答,echo应该是您用于将内容打印到页面的唯一一个。

打印速度稍慢。Var_dump()和print_r()应该只用于调试。

另外值得一提的是,print_r()和var_dump()将默认回显,为print_r()添加第二个参数,至少该参数的值为true,以使其返回,例如print_r($array, true)。

echo和return的区别是:

echo:将立即将值打印到输出。 返回:将函数的输出作为字符串返回。对日志记录等有用。

其他回答

打印和回声或多或少是相同的;它们都是显示字符串的语言结构。两者的区别很细微:print的返回值为1,因此可以在表达式中使用,而echo的返回类型为void;Echo可以接受多个参数,尽管这种用法很少见;Echo比print稍快。(就我个人而言,我总是使用echo,从不打印。)

Var_dump打印变量的详细转储,包括变量的类型和任何子项的类型(如果它是数组或对象)。Print_r以更易于阅读的形式打印变量:字符串不加引号,类型信息被省略,数组大小没有给出,等等。

根据我的经验,在调试时,Var_dump通常比print_r更有用。当你不知道变量中有什么值/类型时,它特别有用。考虑这个测试程序:

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

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

使用print_r,你不能区分0和0.0,或者false和":

array(4) {
  [0]=>
  int(0)
  [1]=>
  float(0)
  [2]=>
  bool(false)
  [3]=>
  string(0) ""
}

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

只是为了补充John的回答,echo应该是您用于将内容打印到页面的唯一一个。

打印速度稍慢。Var_dump()和print_r()应该只用于调试。

另外值得一提的是,print_r()和var_dump()将默认回显,为print_r()添加第二个参数,至少该参数的值为true,以使其返回,例如print_r($array, true)。

echo和return的区别是:

echo:将立即将值打印到输出。 返回:将函数的输出作为字符串返回。对日志记录等有用。

Print_r()用于以人类可读的格式打印数组。

echo

输出一个或多个以逗号分隔的字符串 没有返回值 例如,返回“字符串1”,“字符串2”

打印

只输出一个字符串 返回1,因此可以在表达式中使用 例如,打印“Hello” 或者,if ($expr && print "foo")

print_r ()

输出任何一个值的人类可读表示 不仅接受字符串,还接受包括数组和对象在内的其他类型,并将它们格式化为可读 调试时有用 如果给出第二个可选参数,可以将其输出作为返回值返回(而不是回显)

var_dump()

输出一个或多个用逗号分隔的值的人类可读表示 不仅接受字符串,还接受包括数组和对象在内的其他类型,并将它们格式化为可读 使用不同的输出格式print_r(),例如它也打印值的类型 调试时有用 没有返回值

var_export()

输出任意一个值的人类可读和php可执行表示 不仅接受字符串,还接受包括数组和对象在内的其他类型,并将它们格式化为可读 对print_r()和var_dump()使用不同的输出格式-产生的输出是有效的PHP代码! 调试时有用 如果给出第二个可选参数,可以将其输出作为返回值返回(而不是回显)

注:

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). While var_export() returns valid PHP code allowing values to be read back later, relying on this for production code may make it easier to introduce security vulnerabilities due to the need to use eval(). It would be better to use a format like JSON instead to store and read back values. The speed will be comparable.

print_r()可以打印出值,但如果第二个标志参数被传递并且为TRUE -它将返回打印的结果作为字符串,而不发送到标准输出。 var_dump。如果安装了XDebug调试器,那么输出结果将以更易于阅读和理解的方式格式化。