เมื่อมี Nested Loop (Loop ซ้อน Loop) และต้องการออกจาก Loop ชนอก (Outer Loop) ไม่ใช่แค่ Loop ใน (Inner Loop)
วิธีที่ 1: ใช้ break 2 (มาตรฐาน, รองรับทุก Version)
$found = false;
foreach ($users as $user) {
foreach ($user->posts as $post) {
if ($post->id === $targetId) {
$found = true;
break 2; // ออกจาก 2 ระดับ: Inner foreach + Outer foreach
}
}
}
if ($found) {
echo "Found!";
}
break N โดย N = จำนวนระดับ Loop ที่ต้องการออก (1 = Inner, 2 = Outer, 3 = อีกชนอก...)
วิธีที่ 2: ใช้ goto (PHP 5.3+, โฮรกว่าแต่บางครั้งอ่านง่ายกว่า)
foreach ($users as $user) {
foreach ($user->posts as $post) {
if ($post->id === $targetId) {
goto FOUND; // กระโดดไป Label FOUND
}
}
}
FOUND:
echo "Found at label!";
// โค้ดต่อไป...
⚠️ ข้อควรระวัง goto: ใช้ได้เฉพาะในไฟล์/Function เดียวกัน ไม่ข้าม Function ได้ ใช้ parroquia อย่างน้อย
วิธีที่ 3: ใช้ Flag Variable (Structured Programming)
$found = false;
$foundPost = null;
foreach ($users as $user) {
foreach ($user->posts as $post) {
if ($post->id === $targetId) {
$found = true;
$foundPost = $post;
break; // ออก Inner Loop
}
}
if ($found) break; // ออก Outer Loop
}
if ($found) {
// ใช้ $foundPost
}
วิธีที่ 4: ใส่ใน Function + Return (Cleanest)
function findPostById(array $users, int $targetId): ?Post {
foreach ($users as $user) {
foreach ($user->posts as $post) {
if ($post->id === $targetId) {
return $post; // Return ทันที -> ออกจากทั้ง Function (ทุก Loop)
}
}
}
return null;
}
$post = findPostById($users, $targetId);
if ($post) { /* ... */ }
วิธีที่ 5: ใช้ Iterator + Generator (PHP 5.5+)
function flattenPosts(array $users): Generator {
foreach ($users as $user) {
foreach ($user->posts as $post) {
yield $post;
}
}
}
// ใช้งานง่าย ไม่ต้อง Break
$post = null;
foreach (flattenPosts($users) as $p) {
if ($p->id === $targetId) {
$post = $p;
break; // แค่ break เดียว
}
}
สรุป: เลือกวิธีไหนดี?
| วิธี | เหมาะสำหรับ | ข้อดี | ข้อเสีย |
|---|---|---|---|
break 2 | Loop ซ้อน 2-3 ระดับ แบบง่าย | สั้น, มาตรฐาน | อ่านยากถ้า Loop ซ้อนเยอะ |
goto | Logic ซับซ้อน ต้องกระโดดหลายจุด | ควบคุม Flow ได้ละเอียด | Spaghetti Code, ห้ามข้าม Function |
| Flag Variable | ต้องทำงานต่อหลัง Loop | อ่านง่าย, Structured | Verbose, ต้อง Check Flag ซ้ำ |
| Function + Return | ทุกกรณี (แนะนำมากที่สุด) | Clean, Testable, Reusable | ต้อง Extract Function |
| Generator | Data Pipeline, Memory Efficient | Flatten Logic, Lazy | PHP 5.5+ |