What is the difference between echo, print, and print_r in PHP?



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:

 Live Demo

<?php    $arr = array( "John", "Jacob", "Tom", "Tim");    echo "Array...
";    foreach( $arr as $value ) {       echo "Value = $value
";    }    echo "
Displaying Array Values using print...
";    foreach( $arr as $value ) {       print( "Value = $value
");    }    echo "
Displaying Array Values using print_r...
";    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 )
Updated on: 2020-01-02T06:40:03+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements