开发者

Difference between echo and print_r in php? [duplicate]

This question already has answers here: Closed 10 years ago.

Possible Duplicate:

What’s the diffe开发者_JAVA技巧rence between echo, print, and print_r in PHP?

I am able to use both of these with seemingly the same effect. Is there a difference between the two? And is one preferred over the other?

Thanks!


The difference is that print_r recursively prints an array (or object, but it doesn't look as nice), showing all keys and values. echo does not, and is intended for scalar values.


$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
echo array($a); // returns "Array"
print_r($a); // returns 
Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)


print_r prints human-readable information about a variable, while echo is used only for strings.


Echo just gives the value, print_r gives more information about the variable itself, such as the type of data and the elements in the array, if applicable.


I think you must mean print and echo rather than print_r.... print_r is very clearly different.

First, check out the docs. On the surface, there isn't much difference:

http://php.net/manual/en/function.print.php

http://php.net/manual/en/function.echo.php

The main difference is that print can behave as a function OR a language construct. Either of these will work:

print('Something');
print 'Something';

The former method (with the parenthesis) returns a value after it prints. Now, this begs the question "Why would I need a return value after printing?" The answer is, simply, you don't. The two methods of output are both language constructs, and there isn't a clear performance difference between the two. On an extremely large scale, echo may be marginally faster than print because of the return value, but it is so negligible as to be almost impossible to measure.

There are some tricks you can do to take advantage of the fact that print will behave like a function, though I am hard pressed to give you a real-world example. Here's a not-so-realistic example:

if (print('Test')) {
  // do something after the string is printed
}

Again, not so useful, but there you have it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜