How to Use echo, print, and print_r in PHP
While working with PHP, every developer should know how to use echo, print, as well as print_r. Read our snippet to learn about these crucial parts of PHP.
While working with PHP, every developer should know how to use <kbd class="highlighted">echo</kbd>, <kbd class="highlighted">print</kbd>, and <kbd class="highlighted">print_r</kbd>.
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 not 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 <kbd class="highlighted">echo</kbd> is illustrated below:
php echo usage
<?php
// PHP program for illustrating echo
// Declaring variables and initializing them.
$x = "W3docs ";
$y = "Computer science portal";
// Displaying the value of $x
echo $x, $y;Check out the output:
W3docs Computer science portalUsing print
PHP <kbd class="highlighted">print</kbd> 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 <kbd class="highlighted">echo</kbd> and <kbd class="highlighted">print</kbd>: print is capable of accepting a single argument at a time. You can’t use it as a variable function.
Also, the <kbd class="highlighted">print</kbd> construct is capable of returning merely strings.
For a better perception, take a look at the example below:
php print usage example
<?php
// PHP program for illustrating print
// Declaring a variable and initializing it.
$x = "W3docs";
// Displaying the value of $x
print $x;The output will be:
W3docsUsing print_r()
PHP <kbd class="highlighted">print_r()</kbd> is considered a regular function. It is capable of outputting detailed information about a parameter in a human-understandable format.
The <kbd class="highlighted">print_r()</kbd> function is handy for detecting glitches in the process of the program execution. It is more similar to <kbd class="highlighted">var_dump()</kbd>.
Let’s check out an example of using <kbd class="highlighted">print_r()</kbd>:
php print_r() usage
<?php
// PHP program for illustrating print_r
// Declaring an array
$arr = [
'0' => "W3docs",
'1' => "Computer",
'2' => "Science",
'3' => "Portal",
];
// Displaying the value of $arr
print_r($arr);The output will look as follows:
Array
(
[0] => W3docs
[1] => Computer
[2] => Science
[3] => Portal
)In this snippet, we have shown you the proper ways to use <kbd class="highlighted">echo</kbd>, <kbd class="highlighted">print</kbd>, and <kbd class="highlighted">print_r()</kbd> in PHP. You can use them in your daily programming practice to improve the quality of your work.