tags:

views:

214

answers:

1

Hi,

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?

Thanks!

+14  A: 
break; #breaks out of a loop
continue; #skips rest of current iteration
Jonathan Sampson
It's almost too obvious... :) +1
musicfreak
Eh, we all start somewhere... Thanks!
Alex Mcp
@Alex, we do. Don't get discouraged. We've all been there ;)
Jonathan Sampson