How to create an infinite loop in PHP

4 Answers

0 votes
// Infinite while (true)

$count = 0;

while (true) { // infinite loop
    echo "Iteration: $count\n";

    if ($count === 3) {
        echo "Breaking out of loop...\n";
        break;
    }

    $count++;
}

echo "Loop finished.\n";


/*
run:

Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Breaking out of loop...
Loop finished.

*/

 



answered Apr 11 by avibootz
0 votes
// Infinite for (;;)

$count = 0;

for (;;) { // infinite loop
    echo "Step: $count\n";

    if ($count === 3) {
        echo "Breaking out of loop...\n";
        break;
    }

    $count++;
}

echo "Done.\n";



/*
run:

Step: 0
Step: 1
Step: 2
Step: 3
Breaking out of loop...
Done.

*/

 



answered Apr 11 by avibootz
0 votes
// Infinite do { } while (true)

$count = 0;

do { // infinite loop
    echo "Count: $count\n";

    if ($count === 3) {
        echo "Breaking out of loop...\n";
        break;
    }

    $count++;
} while (true); // infinite loop

echo "Finished.\n";



/*
run:

Count: 0
Count: 1
Count: 2
Count: 3
Breaking out of loop...
Finished.

*/

 



answered Apr 11 by avibootz
0 votes
// Infinite Loop Using goto

$count = 0;

loop_start: // infinite loop

echo "Loop index: $count\n";

if ($count === 3) {
    echo "Breaking out of loop...\n";
    goto loop_end;
}

$count++;

goto loop_start; // infinite loop

loop_end:
echo "Loop ended.\n";



/*
run:

Loop index: 0
Loop index: 1
Loop index: 2
Loop index: 3
Breaking out of loop...
Loop ended.

*/

 



answered Apr 11 by avibootz
...