Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is the difference between echo, print, and print_r in PHP?
In PHP, echo, print, and print_r are used to display output, but they serve different purposes and have distinct characteristics.
Key Differences
| Function | Return Value | Parameters | Purpose |
|---|---|---|---|
echo |
void (no return) | Multiple allowed | Display strings/variables |
print |
1 (always) | Single parameter only | Display strings/variables |
print_r |
true on success | Single parameter | Display array/object structure |
Basic Usage
Here's how each function works with simple strings and variables −
<?php
// Using echo
echo "Hello World
";
echo "Value: ", 25, "
"; // Multiple parameters allowed
// Using print
print "Hello World
";
$result = print "Value: 25
"; // Returns 1, can be used in expressions
echo "Print returned: $result
";
// Using print_r with different data types
$string = "Hello";
$number = 42;
$array = array("apple", "banana", "cherry");
echo "print_r with string:
";
print_r($string);
echo "\nprint_r with array:
";
print_r($array);
?>
Hello World
Value: 25
Hello World
Value: 25
Print returned: 1
print_r with string:
Hello
print_r with array:
Array
(
[0] => apple
[1] => banana
[2] => cherry
)
Complex Data Structures
The real difference becomes apparent when working with arrays and objects −
<?php
$data = array(
"name" => "John",
"age" => 25,
"skills" => array("PHP", "JavaScript", "Python")
);
echo "Using echo:
";
echo $data; // Will show "Array" only
echo "\nUsing print:
";
print $data; // Will show "Array" only
echo "\nUsing print_r:
";
print_r($data); // Shows complete structure
?>
Using echo:
Array
Using print:
Array
Using print_r:
Array
(
[name] => John
[age] => 25
[skills] => Array
(
[0] => PHP
[1] => JavaScript
[2] => Python
)
)
Conclusion
Use echo for fast output of strings and variables, print when you need a return value in expressions, and print_r for debugging arrays and objects to see their internal structure.
Advertisements
