Minggu, 23 Oktober 2011

Difference between echo, print, and print_r in PHP

echo should be d only one u use 2 show content to the page.
print is slightly slower.
var_dump() and print_r() should only be used 2 debug.

For print_r() and var_dump(), they will echo by default, you can add a second argument that evaluates to true to get it to return instead, e.g. print_r($array, TRUE).

For echo, We can't put 2nd argument on it.

The difference between echoing and returning are:
echo: Will immediately print the value to the output.
returning: Will return the function's output as a string. Useful for logging, etc.

echo() outputs one or more strings.
print_r() displays information about a variable in a way that's readable by humans. If given a string, integer or float, the value itself will be printed. If given an array, values will be presented in a format that shows keys and elements.

echo is faster speed than print, but :
‎$result = mysql_query($sql) or print mysql_error(); // valid, works
$result = mysql_query($sql) or echo mysql_error(); // not valid, won't works

echo is a statement
while print is a function
we can't print whole array by using echo or print. For this, we have to use the print_r function

$a=array("ford","benz","bmw","maruthi");
echo ($a);//output Array

$a=array("ford","benz","bmw","maruthi");
print_r ($a);//output Array ( [0] => ford [1] => benz [2] =>bmw [3] => maruthi )

$a=array("ford","benz","bmw","maruthi");
print ($a);//output Array

echo is a language construct.
print is a function.
print_r used to display the contents and structure of objects such as array.

Tidak ada komentar:

Posting Komentar