views:

95

answers:

4

Hi, 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.

+2  A: 
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.

nikic
Yes, but it doesn't seem to work.
ecu
@ecu - how about `$x--` instead?
Eric Petroelje
@nikic, The reason that won't work is because the else clause will fire after the loop is complete -- changing $limit at that point is too late.
Craig Trader
Could you elaborate why this could be so, Craig? At least I don't get why it shouldn't be executed :(
nikic
+6  A: 

Do it in a while() loop instead, and break when you finally hit your $limit

Pickle
Yes; this. For loops are for when you know the number, while loops are for when you don't know the number but you know when you get there.
jeffamaphone
But why you an infinite while loop and then break instead of specifying the condition using while?
nikic
You can easily set a condition within the loop rather than using break $x = true; while ($x) { if (<happy>) { $x=false; } }
Mark Baker
+2  A: 

Use a while loop.

while(count($somearray) < 50 && /*elements remain*/) ...

Donnie
A: 

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...

Oren