Nested loops में outer loop को break करने के लिए PHP में numeric argument के साथ break उपयोग करें।
मूल सिंटैक्स
foreach ($outer as $o) {
foreach ($inner as $i) {
if ($condition) {
break 2; // 2 levels बाहर निकलें
}
}
}
व्यावहारिक उदाहरण
<?php
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
$target = 5;
$found = false;
foreach ($matrix as $rowIndex => $row) {
foreach ($row as $colIndex => $value) {
if ($value === $target) {
echo "$target मिला: row $rowIndex, col $colIndex\n";
$found = true;
break 2; // दोनों loops से बाहर निकलें
}
}
}
if (!$found) {
echo "$target नहीं मिला\n";
}
वैकल्पिक: goto Statement (PHP 5.3+)
<?php
foreach ($outer as $o) {
foreach ($inner as $i) {
if ($condition) {
goto end_loops; // Label पर जाएं
}
}
}
end_loops:
echo "Loops समाप्त हुए\n";
तुलना: break N vs goto
| पहलू | break N | goto |
|---|---|---|
| पठनीयता | स्पष्ट intent | स्पेगेटी कोड का कारण बन सकता है |
| लचीलापन | केवल loops के लिए | कहीं भी जा सकते हैं |
| रखरखाव | आसान | कठिन |
| नेस्टिंग स्तर | गिनना पड़ता है | लेबल नाम |
बेहतर विकल्प: Function में Extract करें
<?php
function findInMatrix(array $matrix, $target): ?array {
foreach ($matrix as $rowIndex => $row) {
foreach ($row as $colIndex => $value) {
if ($value === $target) {
return ['row' => $rowIndex, 'col' => $colIndex];
}
}
}
return null;
}
// उपयोग - clean और testable
$result = findInMatrix($matrix, 5);
if ($result) {
echo "मिला: row {$result['row']}, col {$result['col']}";
} else {
echo "नहीं मिला";
}
अन्य Control Structures के साथ
// while loops
$i = 0;
while ($i < 10) {
$j = 0;
while ($j < 10) {
if ($condition) break 2;
$j++;
}
$i++;
}
// for loops
for ($i = 0; $i < 10; $i++) {
for ($j = 0; $j < 10; $j++) {
if ($condition) break 2;
}
}
// Mixed loops
foreach ($array as $item) {
for ($i = 0; $i < 10; $i++) {
if ($condition) break 2; // foreach और for दोनों से बाहर
}
}
नोट
breakबिना argument के केवल innermost loop से बाहर निकलता है।break 0याbreak 1समान हैं।continueके साथ भी समान syntax काम करता है (continue 2)।