PHP Basics · Beginner Level · Chapter 11
PHP String Formatting
& Output Functions
PHP के सभी Output Functions की पूरी जानकारी — echo, print, printf, sprintf, fprintf, var_dump, print_r, var_export। Debugging और Formatting दोनों।
echoसबसे fast output
%s %dprintf specifiers
var_dumpType + Value दोनों
ob_*Output buffering
📋 इस Article में क्या-क्या है
- echo — सबसे common
- print — Return value वाला
- echo vs print
- printf — Formatted Print
- sprintf — Formatted String
- fprintf — File में Write
- var_dump — Debug Tool
- print_r — Readable Output
- var_export — Valid PHP Output
- Output Buffering ob_*()
1
echo — सबसे Common Output
echo $value;
echo $val1, $val2, $val3; // Multiple — comma से
<?= $value ?> // Short echo tag
echo $val1, $val2, $val3; // Multiple — comma से
<?= $value ?> // Short echo tag
echo — EXAMPLES
<?php// Basic
echo "Hello World";
echo 42;
echo true; // 1
echo false; // (nothing)
echo null; // (nothing)
// Multiple values — comma से (print नहीं कर सकता)
echo "Hello", " ", "World", "!"; // Hello World!
// Variable interpolation
$naam = "Rahul";
echo "नमस्ते, $naam!";
echo "नमस्ते, {$naam}!"; // Complex expressions
// Concatenation
echo "Hello" . " " . $naam;
// HTML में short echo tag
?>
<h1><?= $naam ?></h1>
<p>Price: <?= number_format($price, 2) ?></p>
💡 <?= shorthand: HTML templates में <?= $var ?> सबसे clean है — <?php echo $var; ?> से छोटा। Modern PHP में always preferred।
2
print — Return Value वाला echo
print — EXAMPLES
<?phpprint "Hello World"; // Hello World
print("Hello"); // Parentheses optional
// Returns 1 — expressions में use
$result = print("Hello");
echo $result; // 1
// Ternary में
$condition = true;
$condition ? print("Yes") : print("No");
?>
3
echo vs print — फर्क क्या है?
| Feature | echo | |
|---|---|---|
| Return value | कोई नहीं | हमेशा 1 |
| Multiple args | ✅ echo "a", "b", "c" | ❌ सिर्फ एक |
| Speed | थोड़ा faster | थोड़ा slower |
| Expression use | ❌ | ✅ ternary में |
| Parentheses | Optional | Optional |
| Recommended | ✅ हमेशा | Rarely needed |
✅ Rule: हमेशा echo use करो। print सिर्फ expressions में चाहिए तो use करो — जो बहुत rare है।
4
printf — Formatted Print
int printf( string $format, mixed ...$values )
printf() — FORMAT SPECIFIERS & EXAMPLES
<?php// %s — string, %d — integer, %f — float
printf("नाम: %s, उम्र: %d", "Rahul", 25);
// नाम: Rahul, उम्र: 25
// %.2f — 2 decimal places
printf("Price: ₹%.2f", 99.5); // Price: ₹99.50
printf("PI = %.4f", 3.14159); // PI = 3.1416
// %05d — zero padded integer
printf("Order: %05d", 42); // Order: 00042
// %% — literal percent sign
printf("Discount: %.1f%%", 12.5); // Discount: 12.5%
// %-10s — left aligned, 10 chars wide
printf("%-15s %5s %10s\n", "Product", "Qty", "Price");
printf("%-15s %5d %10.2f\n", "PHP Book", 2, 450.00);
printf("%-15s %5d %10.2f\n", "Laravel", 1, 799.00);
// Product Qty Price
// PHP Book 2 450.00
// Laravel 1 799.00
?>
| Specifier | मतलब | Example → Output |
|---|---|---|
| %s | String | %s, "PHP" → PHP |
| %d | Integer (decimal) | %d, 42 → 42 |
| %f | Float | %f, 3.14 → 3.140000 |
| %.2f | 2 decimal float | %.2f, 3.1 → 3.10 |
| %05d | Zero-padded int | %05d, 42 → 00042 |
| %-10s | Left-aligned 10 wide | %-10s, "Hi" → "Hi " |
| %x | Hexadecimal (lowercase) | %x, 255 → ff |
| %X | Hexadecimal (uppercase) | %X, 255 → FF |
| %b | Binary | %b, 10 → 1010 |
| %o | Octal | %o, 8 → 10 |
| %% | Literal % | %%, → % |
| %1$s | Argument reuse (1st arg) | Swap order |
5
sprintf — Formatted String Return करना
sprintf() — REAL WORLD EXAMPLES
<?php// 1. Order ID generate
$orderId = 42;
$formatted = sprintf("ORD-%06d", $orderId);
echo $formatted; // ORD-000042
// 2. CSS hex color
echo sprintf("#%02x%02x%02x", 255, 128, 0); // #ff8000
// 3. Email template
$body = sprintf(
"Dear %s,\n\nYour order %s of ₹%.2f is confirmed.\n\nThank you!",
"Rahul", "ORD-000042", 1299.00
);
echo $body;
// 4. Log message
function log(string $level, string $msg, ...$args): void {
$formatted = sprintf($msg, ...$args);
echo sprintf("[%s] %s\n", strtoupper($level), $formatted);
}
log("error", "User %d: %s failed", 42, "login");
// [ERROR] User 42: login failed
// 5. Argument swapping — %1$s, %2$s
echo sprintf("%2\$s loves %1\$s", "PHP", "Rahul");
// Rahul loves PHP
?>
✅ sprintf() — store + reuse
$msg = sprintf("Hello %s", $naam);
mail($to, "Subj", $msg);
file_put_contents("log.txt", $msg);
mail($to, "Subj", $msg);
file_put_contents("log.txt", $msg);
ℹ️ printf() — direct print
printf("Hello %s", $naam);
// Store नहीं हो सकता
// Direct output only
// Store नहीं हो सकता
// Direct output only
6
fprintf — File में Formatted Write
fprintf() — FILE WRITE
<?php// CSV file generate करना
$file = fopen("report.csv", "w");
// Header row
fprintf($file, "%s,%s,%s\n", "Name", "Score", "Grade");
// Data rows
$data = [
["Rahul", 95, "A+"],
["Priya", 88, "A"],
];
foreach ($data as [$naam, $score, $grade]) {
fprintf($file, "%s,%d,%s\n", $naam, $score, $grade);
}
fclose($file);
// STDERR में error write
fprintf(STDERR, "Error: %s\n", "DB connection failed");
?>
7
var_dump — Debug Tool #1
var_dump() — ALL TYPES
<?phpvar_dump("Hello"); // string(5) "Hello"
var_dump(42); // int(42)
var_dump(3.14); // float(3.14)
var_dump(true); // bool(true)
var_dump(false); // bool(false)
var_dump(null); // NULL
// Array — length + each element type
var_dump([1, "hello", true]);
// array(3) {
// [0]=> int(1)
// [1]=> string(5) "hello"
// [2]=> bool(true)
// }
// Multiple variables एक साथ
$a = 5; $b = "PHP";
var_dump($a, $b);
// int(5)
// string(3) "PHP"
// Pretty HTML output के लिए
echo "<pre>";
var_dump($complexArray);
echo "</pre>";
?>
⚠️ Production में var_dump() कभी मत छोड़ो! Debug करने के बाद हटा दो — sensitive data expose हो सकता है। Production में error logging use करो।
8
print_r — Human-Readable Array Output
bool print_r( mixed $value, bool $return = false )
print_r() — EXAMPLES
<?php$user = [
"naam" => "Rahul",
"umar" => 25,
"skills" => ["PHP", "MySQL", "Laravel"],
];
// Direct print
print_r($user);
// Array
// (
// [naam] => Rahul
// [umar] => 25
// [skills] => Array
// (
// [0] => PHP
// [1] => MySQL
// [2] => Laravel
// )
// )
// Return as string — log में save
$output = print_r($user, true);
file_put_contents("debug.log", $output);
// HTML में pretty
echo "<pre>" . htmlspecialchars(print_r($user, true)) . "</pre>";
?>
| Function | Types दिखाता है? | Return करता है? | Best For |
|---|---|---|---|
| var_dump() | ✅ हाँ | ❌ नहीं | Type debugging |
| print_r() | ❌ नहीं | ✅ 2nd param true | Array structure |
| var_export() | ✅ हाँ | ✅ 2nd param true | Valid PHP code |
9
var_export — Valid PHP Code Output
var_export() — EXAMPLES
<?phpvar_export("Hello"); // 'Hello'
var_export(42); // 42
var_export(true); // true
var_export(false); // false
var_export(null); // NULL
$config = ["db" => "mysql", "port" => 3306];
var_export($config);
// array ( 'db' => 'mysql', 'port' => 3306, )
// Return as string — cache file बनाना
$phpCode = "<?php return " . var_export($config, true) . ";";
file_put_contents("config.cache.php", $phpCode);
// बाद में: $config = require "config.cache.php";
?>
10
Output Buffering — ob_*() Functions
Output buffering से output को browser को भेजने से पहले capture कर सकते हो। Modify करना, save करना, या conditionally send करना — सब possible।
OUTPUT BUFFERING — EXAMPLES
<?php// ob_start() — buffering शुरू
ob_start();
echo "यह browser को अभी नहीं जाएगा";
echo " — buffer में है";
// ob_get_clean() — content लो और buffer clear करो
$content = ob_get_clean();
echo strtoupper($content); // Uppercase में output
// Template capture करना
function renderTemplate(string $file, array $data): string {
extract($data);
ob_start();
include $file;
return ob_get_clean();
}
$html = renderTemplate("email.php", ["naam" => "Rahul"]);
mail("r@g.com", "Subject", $html);
// ob_*() Functions reference
// ob_start() — buffer शुरू
// ob_end_flush()— buffer send + close
// ob_end_clean()— buffer discard + close
// ob_get_clean()— content get + buffer clear
// ob_get_level()— nesting level
// ob_flush() — buffer send, keep open
?>
✓
Quick Reference — सभी Output Functions
| Function | काम | Returns | Use Case |
|---|---|---|---|
| echo | Output print करना | void | हर जगह — fastest |
| Output print करना | 1 | Expressions में rarely | |
| printf() | Formatted print | int | Aligned tables, direct output |
| sprintf() | Formatted string return | string | Templates, emails, logs |
| fprintf() | File में formatted write | int | CSV, log files |
| var_dump() | Type + Value debug | void | Debug — type check |
| print_r() | Readable array output | bool/string | Debug — structure देखना |
| var_export() | Valid PHP code output | void/string | Config cache, code gen |
| ob_start() | Output buffer शुरू | bool | Template capture |
| ob_get_clean() | Buffer get + clear | string | HTML email, modify output |
✓
निष्कर्ष
PHP Output Functions सीखना important है — सही function सही situation में use करने से code cleaner और efficient बनता है।
echo — हमेशा prefer करो। <?= shorthand HTML में।
sprintf() — printf() से बेहतर — string store और reuse होती है।
var_dump() — type debugging के लिए। Production में हटाओ।
print_r($arr, true) — string return करता है — log में save करो।
ob_start() + ob_get_clean() — template engine का base pattern।
🚀 अगला Chapter: Chapter 12: PHP Date & Time Functions — date(), time(), mktime(), strtotime(), DateTime class। Timestamps और Date formatting।