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

PHPServer Side ProgrammingProgramming

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...\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
)
raja
Published on 27-Dec-2019 12:36:50
Advertisements