Reputation: 4465
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
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
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
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
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