Script Hangs from Infinite Loop

Script appears to hang or produces no output (infinite loop)

Quick Answer

Your script contains an infinite loop where the exit condition is never met. Check loop conditions, counter increments, and boolean flag updates.

Why This Happens

Infinite loops occur when a loop's exit condition is never satisfied. Unlike recursion depth errors, infinite loops silently hang until the maximum execution time is reached. Common causes include forgetting to increment a counter, modifying the wrong variable, or a condition that is logically always true.

The Problem

$items = [1, 2, 3, 4, 5];
$i = 0;
while ($i < count($items)) {
    if ($items[$i] % 2 === 0) {
        array_splice($items, $i, 1); // Removes item but doesn't adjust $i correctly
    }
    $i++;
}

The Fix

// Option 1: Use array_filter
$items = [1, 2, 3, 4, 5];
$items = array_filter($items, fn($item) => $item % 2 !== 0);

// Option 2: Loop backwards
$items = [1, 2, 3, 4, 5];
for ($i = count($items) - 1; $i >= 0; $i--) {
    if ($items[$i] % 2 === 0) {
        array_splice($items, $i, 1);
    }
}

Step-by-Step Fix

  1. 1

    Identify the loop

    Add logging or echo statements inside the loop to track iterations. Check if the loop variable is changing as expected.

  2. 2

    Verify the exit condition

    Check that the loop condition will eventually become false. Verify counter increments, collection modifications, and boolean flag updates.

  3. 3

    Use safe alternatives

    Prefer array functions like array_filter, array_map, or for loops with clear bounds over while loops with complex conditions.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free