How to increase number of iterations from within the loop in php?
I'm working on custom pagination system and encountered following problem. When one of the elements is filtered out of the set, the size of the final array is smaller than needed. Therefore I'm looking for a solution to increase the number of iterations from within the loop to always get array consisting of 50 elements.
$limit = 50; //Number of elements I want to fetch
for($x=0; $x<$limit; $x++){
if ($elementIsNotFiltered) {
开发者_开发知识库 //add element to $someArray;
}
else {
//increase the number of iterations, so even if some elements are filtered out,
//the size of $someArray will always be 50
}
}
Thanks for any help.
Do it in a while()
loop instead, and break
when you finally hit your $limit
Use a while loop.
while(count($somearray) < 50 && /*elements remain*/) ...
else {
++$limit;
}
Tried that?
You may also do the same thing the other way round:
else {
--$x;
}
Or be a little bit more effective:
$x = 0;
while ($x != 50) {
if ($notFiltered) {
++$x;
}
}
If you want to save the counter variable, too, you may use:
while (!isset($array[49])) {
}
The !isset($array[49])
here is only a synonym of count($array) < 50
.
It sounds to me like you're looking for a while
loop - not a for
loop:
while ($items < 50 && [more items to filter]) {
if ([add to array]) {
$items++;
}
}
If you really want to do it in your for
loop you can always modify $x
but this makes your code unreadable and hard to maintain - I would recommend not doing this...
精彩评论