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

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

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


当前回答

打印和回声或多或少是相同的;它们都是显示字符串的语言结构。两者的区别很细微: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] => 
)

其他回答

Echo: Echo是一种不需要使用括号的语言构造,它可以接受任意数量的参数并返回void。

   void echo (param1,param2,param3.....);

   Example: echo "test1","test2,test3";

Print:这是一种不需要使用括号的语言结构,它只接受一个参数并返回

    1 always.

           int print(param1);

           print "test1";
           print "test1","test2"; // It will give syntax error

prinf:这是一个函数,它至少接受一个字符串和格式化样式,并返回输出字符串的长度。

    int printf($string,$s);

    $s= "Shailesh";
    $i= printf("Hello %s how are you?",$s);    
    echo $i;

    Output : Hello Shailesh how are you?
             27



   echo returns void so its execution is faster than print and printf
echo

没有返回类型

print

有返回类型

print_r()

格式化的输出,

它们都是语言结构。Echo返回void, print返回1。Echo被认为比print稍快。

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.