mrpatg
mrpatg

Reputation: 10117

limit and offset foreach loops

Say i want to loop through XML nodes but i want to ignore the first 10 and then limit the number i grab to 10.

$limit=10; //define results limit
$o=20; //define offset
$i=0; //start line counter

foreach($xml->id AS $key => $value){
    $i++;
    if($i > $o){
    //if line number is less than offset, do nothing.
    }else{ 
    if($i == "$limit"){break;} //if line is over limit, break out of loop
    //do stuff here
    }
}

So in this example, id want to start on result 20, and only show 10 results, then break out of the loop. Its not working though. Any thoughts?

Upvotes: 6

Views: 16288

Answers (4)

David
David

Reputation: 57

The answer from soulmerge will go through the loop one too many times. It should be:

foreach (...
    if ($i++ < $o) continue;
    if ($i >= $o + $limit) break;
    // do your stuff here
}

Upvotes: 1

soulmerge
soulmerge

Reputation: 75724

There are multiple bugs in there. It should be

foreach (...
    if ($i++ < $o) continue;
    if ($i > $o + $limit) break;
    // do your stuff here
}

Upvotes: 10

Sabeen Malik
Sabeen Malik

Reputation: 10880

if($i == $limit+$o){break;} 

you should use that cause $limit is reached before $o

Upvotes: 0

Sergey Kuznetsov
Sergey Kuznetsov

Reputation: 8721

You can use next() function for the yours array of elements:

$limit=10; //define results limit
$o=20; //define offset
$i=0; //start line counter

for ($j = 0; $j < $o; $j++) {
  next($xml->id);
}

foreach($xml->id AS $key => $value){
        $i++;
        if($i > $o){
        //if line number is less than offset, do nothing.
        }else{ 
        if($i == "$limit"){break;} //if line is over limit, break out of loop
        //do stuff here
        }
}

More information about next() function: http://php.net/manual/en/function.next.php

Upvotes: 1

Related Questions