Difference between echo, print and print_r in PHP

Last Updated by Pooja Chikara 13-Mar-20

0 223


In PHP, the two basic constructs are used to get outputs which are echo and print. If we talk about echo it is the most basic way to display the result of program in PHP.

What is difference between print_r, print and echo (step by step)

Echo:

echo is not a kind of function, it is a language construct, hence, you can use it with or without parentheses such as echo or echo(). It do not return any value.

With the help of echo, we can display the value of a variable, string with single quotes or with double quotes and multiple strings separated by commas.

PHP Echo Example:

<?php
$myString1 = "Welcome to codingtag!";
$myString2 = 'Stay here for a variety of useful code.';
echo $myString1.'<br>';
echo $myString2;
echo "<h5>I love using PHP!</h5>";
?>

Result:

Difference between echo, print and print_r in PHP


print():

print is not a function. It is also a language construct like echo but it is always return a value either 0 or 1 so, we can use it to print the result of any regular expression.

As compared to echo, the execution of print is slow. It can display only one string at a time.

PHP Print Example:

<?php
$myString1 = "Welcome to codingtag!";
$myString2 = 'Stay here for a variety of useful code.';
print($myString1);
print '<br>'.$myString2;
print "<h5>I love using PHP!</h5>";
?>

Result:

Difference between echo, print and print_r in PHP


print_r:

It is a php function which is mainly used to print the PHP array or object in a more readable format. It is mostly used to check the possibilities of errors in to the code.

PHP print_r Example:

<?php
$myarray = array("Welcome","to","condingtag");
print_r($myarray);
?>

Result:

Difference between echo, print and print_r in PHP


Another Example:

<?php
$myarray = array("Welcome","to","condingtag");
echo "<pre>";
print_r($myarray);
?>

Result:

Difference between echo, print and print_r in PHP


Share:


Leave a Reply


Comments
    Waiting for your comments