PHP Loops क्या है?
Complete Guide in Hindi
PHP के सभी Loops की पूरी जानकारी — for, while, foreach, do-while, और nested loops। break और continue के साथ। Real-world examples के साथ।
📋 इस Article में क्या-क्या है
- Loop क्या है?
- for loop
- while loop
- do-while loop
- foreach loop
- Nested Loops
- break statement
- continue statement
- Comparison & FAQ
- Real World Examples
Loop एक code block को बार-बार execute करता है जब तक कोई condition true रहे। repetitive tasks को automatically करने के लिए — 100 students के नाम print करना, table बनाना, array process करना।
For Loop
जब पहले से पता हो कितनी बार चलना है। Counting loops के लिए best।
While Loop
जब तक condition true हो तब तक। Count पहले से पता न हो।
Do-While Loop
कम से कम एक बार ज़रूर चलेगा। User input validation के लिए।
Foreach Loop
Arrays और objects के लिए specially बनाया। हर element पर एक बार।
// code यहाँ लिखो — हर iteration में चलेगा
}
// Example:
for ($i = 0; $i < 5; $i++) {
// $i = 0,1,2,3,4 — 5 बार चलेगा
}
| Part | काम | Example |
|---|---|---|
| $init | Counter initialize करो — एक बार | $i = 0 |
| $condition | हर iteration में check — false होने पर stop | $i < 10 |
| $increment | हर iteration के बाद counter change | $i++ या $i+=2 |
// 1 से 5 तक print करो
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
}
// Output: 1 2 3 4 5
// 0 से 10 तक — step 2
for ($i = 0; $i <= 10; $i += 2) {
echo $i . " ";
}
// Output: 0 2 4 6 8 10
// Countdown — reverse loop
for ($i = 10; $i >= 1; $i--) {
echo $i . " ";
}
// Output: 10 9 8 7 6 5 4 3 2 1
// Array index access के साथ
$fruits = ["Apple", "Mango", "Banana"];
for ($i = 0; $i < count($fruits); $i++) {
echo $i . ": " . $fruits[$i] . "\n";
}
// 0: Apple, 1: Mango, 2: Banana
?>
// 1. Multiplication Table (पहाड़ा)
$num = 7;
echo "=== $num का पहाड़ा ===\n";
for ($i = 1; $i <= 10; $i++) {
echo $num . " × " . $i . " = " . ($num * $i) . "\n";
}
// 2. HTML table rows generate करना
echo "<table border='1'>";
for ($row = 1; $row <= 5; $row++) {
echo "<tr><td>Row $row</td><td>" . ($row * 10) . "</td></tr>";
}
echo "</table>";
// 3. Star pattern
for ($i = 1; $i <= 5; $i++) {
echo str_repeat("★", $i) . "\n";
}
// ★
// ★★
// ★★★
// ★★★★
// ★★★★★
?>
// code — condition true रहने तक चलेगा
// ⚠️ condition को change करो — infinite loop से बचाओ!
}
// Basic while loop
$i = 1;
while ($i <= 5) {
echo $i . " ";
$i++; // ⚠️ यह ज़रूरी है — वरना infinite loop!
}
// Output: 1 2 3 4 5
// Fibonacci sequence
$a = 0; $b = 1;
while ($a < 100) {
echo $a . " ";
[$a, $b] = [$b, $a + $b]; // Swap + add
}
// Output: 0 1 1 2 3 5 8 13 21 34 55 89
?>
// 1. Database rows fetch (simulation)
// $result = $pdo->query("SELECT * FROM users");
// while ($row = $result->fetch()) {
// echo $row["naam"];
// }
// 2. File read करना
// $file = fopen("data.txt", "r");
// while (!feof($file)) {
// $line = fgets($file);
// echo $line;
// }
// 3. Number guessing game
$secret = 42;
$guess = 0;
$attempts = 0;
$guesses = [10, 60, 35, 42]; // simulation
while ($guess !== $secret) {
$guess = $guesses[$attempts];
$attempts++;
if ($guess < $secret) echo "ज़्यादा guess करो\n";
elseif ($guess > $secret) echo "कम guess करो\n";
}
echo "सही! $attempts attempts में मिला";
?>
// code — पहले चलेगा
} while ($condition); // बाद में check होगा
✅ do-while — कम से कम एक बार
do {
echo $i; // 10 print होगा!
$i++;
} while ($i < 5);
// condition false है, पर once runs
❌ while — condition false तो नहीं चलेगा
while ($i < 5) {
echo $i; // कभी नहीं चलेगा!
$i++;
}
// No output
// 1. Menu system — कम से कम एक बार दिखाओ
$choice = 0;
$inputs = [1, 2, 4]; // simulation
$idx = 0;
do {
echo "=== Menu ===\n1. Add\n2. View\n3. Delete\n4. Exit\n";
$choice = $inputs[$idx++]; // user input simulation
echo "Choice: $choice\n";
} while ($choice !== 4);
echo "Goodbye!";
// 2. OTP retry — कम से कम एक attempt
$correctOTP = "1234";
$attempts = 0;
$otps = ["9999", "5555", "1234"];
do {
$enteredOTP = $otps[$attempts];
$attempts++;
echo "OTP entered: $enteredOTP\n";
} while ($enteredOTP !== $correctOTP && $attempts < 3);
echo $enteredOTP === $correctOTP ? "✅ Login successful" : "❌ Failed";
?>
foreach ($array as $value) { ... }
// Form 2 — key और value दोनों
foreach ($array as $key => $value) { ... }
// 1. Indexed Array
$fruits = ["Apple", "Mango", "Banana"];
foreach ($fruits as $fruit) {
echo $fruit . "\n"; // Apple, Mango, Banana
}
// 2. Index के साथ
foreach ($fruits as $index => $fruit) {
echo "$index: $fruit\n"; // 0: Apple, 1: Mango...
}
// 3. Associative Array
$user = ["naam" => "Rahul", "umar" => 25, "city" => "Delhi"];
foreach ($user as $key => $value) {
echo "$key: $value\n";
}
// 4. Multidimensional Array
$students = [
["naam" => "Rahul", "marks" => 95],
["naam" => "Priya", "marks" => 88],
];
foreach ($students as $s) {
echo "{$s['naam']}: {$s['marks']}\n";
}
?>
// Reference से modify — & symbol
$prices = [100, 200, 300];
foreach ($prices as &$price) {
$price = $price * 1.1; // 10% GST add
}
unset($price); // ⚠️ Reference unset करना ज़रूरी!
print_r($prices); // [110, 220, 330]
// Product list HTML generate
$products = [
["name" => "PHP Book", "price" => 450, "stock" => 5],
["name" => "Laravel", "price" => 799, "stock" => 0],
["name" => "MySQL", "price" => 299, "stock" => 12],
];
foreach ($products as $p) {
$badge = $p["stock"] > 0 ? "✅ In Stock" : "❌ Out";
echo "{$p['name']} — ₹{$p['price']} $badge\n";
}
?>
// 1. Multiplication Table — All
for ($i = 1; $i <= 3; $i++) { // outer — row
for ($j = 1; $j <= 3; $j++) { // inner — column
echo $i * $j . "\t";
}
echo "\n";
}
// 1 2 3
// 2 4 6
// 3 6 9
// 2. 2D Array (Students per class)
$classes = [
"10A" => ["Rahul", "Priya"],
"10B" => ["Amit", "Neha", "Raj"],
];
foreach ($classes as $class => $students) {
echo "Class $class:\n";
foreach ($students as $student) {
echo " - $student\n";
}
}
?>
// Basic break — first negative number find करो
$nums = [5, 8, 3, -2, 7, -4];
foreach ($nums as $num) {
if ($num < 0) {
echo "First negative: $num";
break; // मिल गया, loop बंद करो
}
}
// Output: First negative: -2
// break 2 — nested loop में outer loop भी break
for ($i = 0; $i < 3; $i++) {
for ($j = 0; $j < 3; $j++) {
if ($i == 1 && $j == 1) {
break 2; // दोनों loops बंद!
}
echo "($i,$j) ";
}
}
// (0,0) (0,1) (0,2) (1,0)
?>
// Even numbers only print करो
for ($i = 1; $i <= 10; $i++) {
if ($i % 2 !== 0) {
continue; // Odd है — skip करो
}
echo $i . " ";
}
// Output: 2 4 6 8 10
// Empty values skip करना
$names = ["Rahul", "", "Priya", " ", "Amit"];
foreach ($names as $naam) {
if (trim($naam) === "") {
continue; // Empty skip
}
echo ucwords(trim($naam)) . "\n";
}
// Rahul, Priya, Amit (empty skip)
// Out of stock products skip
$products = [
["name" => "Book", "stock" => 5],
["name" => "Pen", "stock" => 0],
["name" => "Bag", "stock" => 3],
];
foreach ($products as $p) {
if ($p["stock"] === 0) continue; // Out of stock skip
echo "✅ {$p['name']} ({$p['stock']} left)\n";
}
// ✅ Book (5 left), ✅ Bag (3 left)
?>
| Loop | Use करो जब | Example |
|---|---|---|
| for | Count पहले से पता हो। Index-based। Counting up/down। | 1-100 print, table rows, patterns |
| while | Count पता न हो। Condition-based। DB rows fetch। | File read, user input, game loop |
| do-while | कम से कम एक बार ज़रूर चलाना हो। | Menu show, OTP retry, validation |
| foreach | Array/object traverse करना हो। | Product list, students, config |
| break | Condition मिलने पर loop बंद करना। | Search stop, error found |
| continue | Current iteration skip, loop जारी रखना। | Even numbers, valid data only |
$students = [
["naam" => "Rahul", "marks" => [85, 90, 78, 92, 88]],
["naam" => "Priya", "marks" => [92, 95, 88, 96, 90]],
["naam" => "Amit", "marks" => [45, 52, 38, 60, 42]],
["naam" => "Neha", "marks" => [70, 75, 68, 72, 80]],
];
$subjects = ["Math", "Science", "English", "Hindi", "Computer"];
$classTopScore = 0;
$topperNaam = "";
// foreach — हर student process करो
foreach ($students as $student) {
$naam = $student["naam"];
$marks = $student["marks"];
$total = array_sum($marks);
$avg = round($total / count($marks), 1);
// while — grade determine करो
$grade = "F";
if ($avg >= 90) $grade = "A+";
elseif ($avg >= 80) $grade = "A";
elseif ($avg >= 70) $grade = "B";
elseif ($avg >= 60) $grade = "C";
elseif ($avg >= 50) $grade = "D";
// Failed student — continue (skip display)
if ($grade === "F") {
echo "⚠️ $naam: FAIL (avg: $avg)\n";
continue;
}
// for — हर subject print करो
echo "\n=== $naam | Grade: $grade | Avg: $avg ===\n";
for ($i = 0; $i < count($subjects); $i++) {
echo " {$subjects[$i]}: {$marks[$i]}\n";
}
// Class topper track करो
if ($total > $classTopScore) {
$classTopScore = $total;
$topperNaam = $naam;
}
}
echo "\n🏆 Class Topper: $topperNaam ($classTopScore total)";
?>
PHP Loops programming का core concept है। Arrays, database results, user interfaces — सब में loops ज़रूरी हैं। सही loop choose करना important है।
for — count पता हो, index चाहिए। for ($i=0; $i<n; $i++)
while — count पता न हो। Condition true रहने तक। ⚠️ infinite loop से बचो।
do-while — minimum एक बार ज़रूर चलाना हो। Menu, OTP।
foreach — Arrays के लिए best। Key-value दोनों access।
break — Loop बंद करो। break 2 = outer loop भी।
continue — Current skip, loop जारी। continue 2 = outer।