PHP में output के तीन मुख्य constructs: echo, print, और print_r()।
त्वरित तुलना
| विशेषता | echo | print | print_r() |
| Type | Language construct | Language construct | Function |
| Return value | कोई नहीं (void) | हमेशा 1 | true (या string यदि second param true) |
| Parameters | Multiple (comma separated) | Single expression | Variable + optional return flag |
| Output style | Raw output | Raw output | Structured, human-readable |
| Arrays/Objects | ❌ "Array" / "Object" | ❌ "Array" / "Object" | ✅ Full structure |
| Speed | सबसे तेज़ | थोड़ा धीमा | धीमा (formatting के कारण) |
echo - Simple Output
<?php
// Multiple arguments (comma) - no parentheses needed
echo 'Hello', ' ', 'World', PHP_EOL; // Hello World
// Variables
$name = 'अमित';
echo "नमस्ते, $name!"; // नमस्ते, अमित!
// Cannot use in expression context
// $result = echo 'test'; // Parse error!
print - Expression Context में उपयोगी
<?php
// Single argument
print 'Hello World'; // 1 return करता है
// Expression में उपयोग कर सकते हैं
$result = print "Hello"; // $result = 1, prints "Hello"
// Ternary में
$condition && print "Condition met\n"; // Short-circuit: prints only if true
// लेकिन multiple arguments नहीं
// print 'a', 'b'; // Parse error!
print_r() - Debugging के लिए Structured Output
<?php
$arr = ['name' => 'अमित', 'age' => 25, 'skills' => ['PHP', 'Python']];
// Default: direct output
print_r($arr);
/*
Array
(
[name] => अमित
[age] => 25
[skills] => Array
(
[0] => PHP
[1] => Python
)
)
*/
// Second parameter true = return string
$output = print_r($arr, true);
file_put_contents('debug.log', $output);
// Objects के लिए भी
class User {
public $name = 'अमित';
private $password = 'secret';
}
print_r(new User());
// Shows all properties (including private in PHP 5+)
var_dump() vs print_r()
| पहलू | var_dump() | print_r() |
| Type information | हाँ (int, string, length, आदि) | नहीं |
| Null values | स्पष्ट रूप से दिखाता है | खाली दिख सकता है |
| Boolean | bool(true) | 1 / खाली |
| Resource | Resource ID दिखाता है | Resource ID दिखाता है |
| Recursion protection | हाँ | हाँ |
Modern Alternatives (PHP 7+)
<?php
// JSON encoding (APIs, logs के लिए)
echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
// var_export (valid PHP code)
echo var_export($data, true);
// Debug libraries: Symfony VarDumper, Laravel dd()
// dump($data); // Symfony - beautiful, collapsible
// dd($data); // Laravel - dump and die
सर्वोत्तम अभ्यास
- Production output:
echo (fastest, no return value overhead)
- Expression context:
print (rarely needed)
- Debugging arrays/objects:
print_r() या var_dump()
- Logging/Storage:
print_r($var, true) या var_export($var, true)
- API responses:
json_encode()