The print and echo are both language constructs to display strings. The echo has a void return type, whereas print has a return value of 1 so it can be used in expressions. The print_r is used to display human-readable information about a variable.
Example
Let us now see an example that displays output using echo, print, and print_r:
$arr = array( “John”, “Jacob”, “Tom”, “Tim”);
echo “Array…n”;
foreach( $arr as $value ) {
echo “Value = $value n”;}
echo “nDisplaying Array Values using print…n”;
foreach( $arr as $value ) {
print( “Value = $value n”);
echo “nDisplaying Array Values using print_r…n”;
print_r($arr);
Output
This will produce the following output−
Array…
Value = John
Value = Jacob
Value = Tom
Value = Tim
Displaying Array Values using print…
Value = John
Value = Jacob
Value = Tom
Value = Tim
Displaying Array Values using print_r…
Array (
[0] => John
[1] => Jacob
[2] => Tom
[3] => Tim
)
- echo: echo is not a function rather it is described as a language construct. It accepts a list of arguments (multiple arguments can be passed) and returns no value or returns void. It cannot be used as a variable function in PHP. It is used to display the output of parameters that are passed to it. It displays the outputs of one or more strings separated by commas.
$x = “Vkprogramming”;
$y = “Computer science portal”;
// Display the value of $x
echo $x, $y;
Output:
Vkprogramming Computer science portal
- print: It is not a real function. it is a language construct but always returns the value 1. So it can be used as an expression. Unlike echo, print accepts only one argument at a time. It cannot be used as a variable function in PHP. The print outputs only the strings. It is slow compared to that of echo.
Example:
$x = “Vkprogramming”;
// Display the value of $x
print $x;
Output:
Vkprogramming
print_r(): print_r() is a regular function. It outputs detailed information about the parameter in a format with its type (of an array or an object), which can be easily understandable by humans. In this function, the output gets stored on the internal buffer when the return parameter is passed. If pass then returns parameter to TRUE, print_r() would return the complete information rather than just print it. During walk-through this function helps in identifying any of the glitches while executing the program. It is more similar to the var_dump() function.
Example:
$arr = array(‘0’ => “Vkprogramming”,
‘1’ => “Computer”,
‘2’ => “Science”,
‘3’ => “Portal”);
print_r($arr);
Output:
Array(
[0] => Vkprogramming
[1] => Computer
[2] => Science
[3] => Portal
)
Example:
$a = “Vkprogramming”;
$b = array(‘0’ => “Vk”, ‘1’ => “for”, ‘2’ => “programming”);
$c = 3.14;
$d = 7;
// Single argument
print “n$an”;
// Multiple argument
echo $c + $d . “n”;
// Return with internal output buffering
print_r($b);
Output:
Vkprogramming
10.14
Array(
[0] => Vk
[1] => for
[2] => Programming
)