Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

Break Outer Loop ใน PHP (Nested Loops)

เมื่อมี 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 2Loop ซ้อน 2-3 ระดับ แบบง่ายสั้น, มาตรฐานอ่านยากถ้า Loop ซ้อนเยอะ
gotoLogic ซับซ้อน ต้องกระโดดหลายจุดควบคุม Flow ได้ละเอียดSpaghetti Code, ห้ามข้าม Function
Flag Variableต้องทำงานต่อหลัง Loopอ่านง่าย, StructuredVerbose, ต้อง Check Flag ซ้ำ
Function + Returnทุกกรณี (แนะนำมากที่สุด)Clean, Testable, Reusableต้อง Extract Function
GeneratorData Pipeline, Memory EfficientFlatten Logic, LazyPHP 5.5+