PHP Basics · Beginner Level · Chapter 9

PHP Loops क्या है?
Complete Guide in Hindi

PHP के सभी Loops की पूरी जानकारी — for, while, foreach, do-while, और nested loops। break और continue के साथ। Real-world examples के साथ।

🔢 for loop ⏳ while loop 📦 foreach loop 🔄 do-while loop ⏹️ break/continue
4Types of Loops
foreachArrays के लिए best
breakLoop बाहर निकलो
continueStep skip करो

📋 इस Article में क्या-क्या है

  1. Loop क्या है?
  2. for loop
  3. while loop
  4. do-while loop
  5. foreach loop
  6. Nested Loops
  7. break statement
  8. continue statement
  9. Comparison & FAQ
  10. Real World Examples
1
Loop क्या है?

Loop एक code block को बार-बार execute करता है जब तक कोई condition true रहे। repetitive tasks को automatically करने के लिए — 100 students के नाम print करना, table बनाना, array process करना।

बिना loop के 100 lines लिखने की जगह loop में 3-4 lines। यही है loop की power — DRY (Don't Repeat Yourself) principle।
Loop = एक काम को बार-बार करना। जैसे teacher 30 students को एक-एक करके marks देता है।
for

For Loop

जब पहले से पता हो कितनी बार चलना है। Counting loops के लिए best।

while

While Loop

जब तक condition true हो तब तक। Count पहले से पता न हो।

do-while

Do-While Loop

कम से कम एक बार ज़रूर चलेगा। User input validation के लिए।

foreach

Foreach Loop

Arrays और objects के लिए specially बनाया। हर element पर एक बार।


2
for Loop — Fixed Count Repetition
for
()

for loop

जब exact count पहले से पता हो — for loop best है। Init, condition, और increment — तीनों एक line में। Counting, indexing, tables के लिए।

Fixed Count Index Access Most Controlled
for ($init; $condition; $increment) {
  // code यहाँ लिखो — हर iteration में चलेगा
}

// Example:
for ($i = 0; $i < 5; $i++) {
  // $i = 0,1,2,3,4 — 5 बार चलेगा
}
PartकामExample
$initCounter initialize करो — एक बार$i = 0
$conditionहर iteration में check — false होने पर stop$i < 10
$incrementहर iteration के बाद counter change$i++ या $i+=2
$i = 0 (init — एक बार)
$i < 5? (condition check)
YES
loop body execute
$i++ (increment)
↑ back to condition
NO → Loop End
for LOOP — BASIC EXAMPLES
<?php
// 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
?>
for LOOP — REAL WORLD EXAMPLES
<?php
// 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";
}
// ★
// ★★
// ★★★
// ★★★★
// ★★★★★
?>

3
while Loop — Condition-Based Repetition
whl
()

while loop

जब तक condition true रहे — loop चलता रहेगा। Count पहले से पता नहीं — जैसे user input लेना, file read करना, database rows fetch करना।

Condition-based Unknown count Infinite loop risk!
while ($condition) {
  // code — condition true रहने तक चलेगा
  // ⚠️ condition को change करो — infinite loop से बचाओ!
}
while LOOP — BASIC EXAMPLES
<?php
// 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
?>
while LOOP — REAL WORLD EXAMPLES
<?php
// 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 में मिला";
?>
⚠️ Infinite Loop से बचो! while loop में हमेशा condition को कहीं न कहीं false बनाओ — $i++ या $count--। बिना इसके loop कभी नहीं रुकेगा और server crash हो जाएगा।

4
do-while Loop — Minimum एक बार
do
whl

do-while loop

while loop जैसा — लेकिन condition बाद में check होती है। मतलब body कम से कम एक बार ज़रूर execute होती है — condition चाहे true हो या false।

Min once Post-condition User Input
do {
  // code — पहले चलेगा
} while ($condition); // बाद में check होगा

✅ do-while — कम से कम एक बार

$i = 10;
do {
  echo $i; // 10 print होगा!
  $i++;
} while ($i < 5);
// condition false है, पर once runs

❌ while — condition false तो नहीं चलेगा

$i = 10;
while ($i < 5) {
  echo $i; // कभी नहीं चलेगा!
  $i++;
}
// No output
do-while — REAL WORLD EXAMPLES
<?php
// 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";
?>

5
foreach Loop — Arrays के लिए Best
each
()

foreach loop

Arrays और objects के लिए specially designed। हर element को automatically traverse करता है — index manage करने की ज़रूरत नहीं। PHP का सबसे common loop।

Arrays Only Most Common Key-Value Access
// Form 1 — सिर्फ value
foreach ($array as $value) { ... }

// Form 2 — key और value दोनों
foreach ($array as $key => $value) { ... }
foreach — INDEXED, ASSOCIATIVE, MULTIDIMENSIONAL
<?php
// 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";
}
?>
foreach — REFERENCE MODIFY & REAL WORLD
<?php
// 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";
}
?>
💡 foreach vs for for Arrays: Arrays के लिए हमेशा foreach prefer करो। for ($i=0; $i<count($arr); $i++) से ज़्यादा readable, safer, और faster है। for loop use करो जब index-based operations ज़रूरी हों जैसे reverse iterate या skip करना।

6
Nested Loops — Loop के अंदर Loop
एक loop के अंदर दूसरा loop — Nested Loop। 2D arrays, tables, patterns, matrix के लिए। Outer loop एक बार चले = Inner loop पूरा चलेगा।
NESTED LOOPS — EXAMPLES
<?php
// 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";
  }
}
?>
⚠️ Performance Warning: 3+ nested loops बहुत slow हो सकते हैं। 1000 elements × 1000 = 1,000,000 iterations! Deep nesting से बचो — helper functions use करो।

7
break — Loop से बाहर निकलना
brk
()

break statement

Loop को तुरंत बंद करता है — बाकी iterations skip। जैसे item ढूँढ लिया, अब loop जारी रखने की ज़रूरत नहीं। switch में भी use होता है।

Loop Exit Search Optimization break 2 = outer loop
break — EXAMPLES
<?php
// 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)
?>

8
continue — Current Iteration Skip करना
cont
()

continue statement

Current iteration को skip करता है और अगले पर जाता है। Loop बंद नहीं होता। Odd/Even filtering, invalid data skip करना।

Skip Current Loop Continues continue 2 = outer
continue — EXAMPLES
<?php
// 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)
?>

9
Comparison — कौन सा Loop कब Use करें?
LoopUse करो जबExample
forCount पहले से पता हो। Index-based। Counting up/down।1-100 print, table rows, patterns
whileCount पता न हो। Condition-based। DB rows fetch।File read, user input, game loop
do-whileकम से कम एक बार ज़रूर चलाना हो।Menu show, OTP retry, validation
foreachArray/object traverse करना हो।Product list, students, config
breakCondition मिलने पर loop बंद करना।Search stop, error found
continueCurrent iteration skip, loop जारी रखना।Even numbers, valid data only
Q: for और foreach में क्या फर्क है?
for loop general-purpose है — counter manually manage करना पड़ता है। foreach arrays के लिए specifically बना है — automatic iteration, key-value access, cleaner code। Arrays के लिए foreach prefer करो।
Q: while और do-while में क्या फर्क है?
while पहले condition check करता है — condition false हो तो एक बार भी नहीं चलेगा। do-while पहले चलता है, फिर condition check करता है — कम से कम एक बार ज़रूर चलेगा। Menu systems और user input के लिए do-while बेहतर है।
Q: break और continue में क्या फर्क है?
break — loop को पूरी तरह बंद कर देता है। continue — सिर्फ current iteration skip करता है, loop आगे चलता रहता है। break 2 और continue 2 nested loops में outer loop को affect करते हैं।
Q: Infinite loop कैसे रुकाएं?
while/do-while में हमेशा loop condition को change करो। अगर accidentally infinite loop हो जाए — browser में page reload करो या PHP execution time limit set करो: set_time_limit(30)। Production में max_execution_time php.ini में set होती है।

10
Combined Real World Example — Report Generate करना
COMBINED — Student Report Card
<?php
$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)";
?>
Pattern: foreach (students) → for (subjects) → continue (fail skip) → while-style grade check — सभी loops मिलकर complete solution।

निष्कर्ष (Conclusion)

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।

🚀 अगला Chapter: Chapter 10: PHP Functions — Functions define करना, parameters, return values, default values, variadic functions, arrow functions। PHP का सबसे powerful feature।