Thingamajig
Thingamajig

Reputation: 4465

How can I have a loop run until I have a select number of results?

IN PHP: I have a for loop running through an array and if the value of each key does not match the value I'm looking for, I skip it.

How can I create a loop that runs until I have found 20 of the values that I am looking for. So I can't have it be for($i=0;$i<50;$i++) because of the first 50, there may be only 2 values that match. So it needs to run until 20 match.

UPDATE: I also need to iterate through the array, so I still need to check every value like this: $news_posts[$i]['category']; if category is what i'm looking for then that's 1. If its not, then I skip it. I need 20.

Upvotes: 1

Views: 178

Answers (6)

Jake Sankey
Jake Sankey

Reputation: 5137

Simply break out of the loop when some condition is true.

for ($i = 0; $i < $countValue; $i++)
{
   //do something

   if ($i == 10) break;
}

Upvotes: 0

NullUserException
NullUserException

Reputation: 85468

You can use more than one condition:

for ($i=0, $found=0; $i<count($news_posts) && $found<20; ++$i)
{
    if ($news_posts[$i]['category'] == 'something')
    {
        ++$found;
        // do the rest of your stuff
    }
}

This will loop through everything in $news_posts, but stop earlier if 20 are found.

A for loop has three parts (initialization; condition; increment). You can have multiple statements (or none) in any of them. For example, for (;;) is equivalent to while (true).

Upvotes: 4

earl3s
earl3s

Reputation: 2373

$count = 0;
$RESULT_COUNT = 20;
while($count < $RESULT_COUNT) {
    // your code to determine if result is found

    if($resultFound) {
        $count++;
    }

    if($resultsEnd) { // check here to see if you have any more values to search through
        break;
    }
}

Upvotes: 0

alpera
alpera

Reputation: 509

$count = 0;
while(true){
if($count>20)
    break;
...
}

Upvotes: 0

Adam Plocher
Adam Plocher

Reputation: 14233

This will work. Just be careful, if your count never gets higher than 19, the loop will run forever.

$count = 0;
while ($count < 20) 
{
    if (whatever)
    {
        $count++;
    }
}

Upvotes: 0

Kovo
Kovo

Reputation: 1717

$foundValues = 0;

while($foundValues < 20)
{
   //Do your magic here
}

Upvotes: 0

Related Questions