Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I break a for-loop in PHP when conditions are met?

Tags:

loops

php

primes

I'm diligently plugging away at some code that checks for divisibility (yes, it's to generate primes) and I want to know how to stop a for... loop if the condition is met once. Code like this:

$delete = array();
foreach ( $testarray as $v ) {
    for ( $b = 2; $b < $v; $b++ ) {
        if ( $v % $b == 0 ) {
            $delete []= $v;
        }
    }

So $testarray is integers 1-100, and the $delete array will be filtered against the $testarray. Currently though, a number like 12 is being added to $delete multiple times because it's divisible by 2, 3, 4, and 6. How can I save my computer's time by skipping ahead when the criteria matched once?

like image 334
Alex Mcp Avatar asked Jun 28 '09 00:06

Alex Mcp


People also ask

Can you break in a for loop?

Using break as well as continue in a for loop is perfectly fine. It simplifies the code and improves its readability.

Is there a break statement in PHP?

PHP break statement breaks the execution of the current for, while, do-while, switch, and for-each loop. If you use break inside inner loop, it breaks the execution of inner loop only. The break keyword immediately ends the execution of the loop or switch structure.

Does PHP return stop a loop?

PHP 7 requires a return . A break; is not needed because the loop ends on return . A break; is usually used in a switch or loop whenever you have found your needed item.


1 Answers

break; #breaks out of a loop
continue; #skips rest of current iteration
  • http://us3.php.net/manual/en/control-structures.break.php
  • http://us3.php.net/manual/en/control-structures.continue.php
like image 198
Sampson Avatar answered Sep 19 '22 19:09

Sampson