w3docs logo
  1. Snippets
  2. PHP
  3. How to Use echo, print, and print_r in PHP

How to Use echo, print, and print_r in PHP

While working with PHP, every developer should know how to use echo, print, and print_r.

This snippet is dedicated to exploring these essential parts of the PHP programming language.

Using echo

PHP echo is considered a language construct and not a function. It is capable of accepting a list of arguments. Yet, it will now return any value.

You can’t use it as a variable function in PHP. However, you can apply it for displaying the output of parameters, passed to it.

The example of using PHP echo is illustrated below:

<?php

// PHP program for illustrating echo 

// Declaring variable and initializing it. 
$x = "W3docs ";
$y = "Computer science portal";

// Displaying the value of $x 
echo $x, $y;
?>

Check out the output:

W3docs Computer science portal

Using print

PHP print is not a real function, either. It is considered a language construct.

Yet, unlike echo, it always returns the value 1. It can easily be used as an expression. There is another difference between echo and print: print is capable of accepting a single argument at a time. You can’t use it as a variable function.

Also, the print construct is capable of returning merely strings.

For a better perception, take a look at the example below:

<?php

// PHP program for illustrating echo 

// Declaring variable and initializing it. 
$x = "W3docs";

// Displaying the value of $x 
print $x;
?>

The output will be:

W3docs

Using print_r()

PHP print_r() is considered a regular expression. It is capable of outputting the detailed information about a parameter in a human-understandable format.

The print_r() regular expression is handy for detecting glitches in the process of the program execution. It is more similar to var_dump().

Let’s check out an example of using print_r():

<?php

// PHP program for illustrating echo 

// Declaring an array 
$arr = array(
  '0' => "W3docs",
  '1' => "Computer",
  '2' => "Science",
  '3' => "Portal"
);

// Displaying the value of $x 
print_r($arr);
?>

The output will look as follows:

Array
(
    [0] => W3docs
    [1] => Computer
    [2] => Science
    [3] => Portal
)

In this snippet, we represented to you the most proper ways of using echo, print, and print_r() in PHP. You can use them in your daily programming practice to improve the quality of your work.

Do you find this helpful?