Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

limit and offset foreach loops

Tags:

php

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?

like image 339
mrpatg Avatar asked Feb 28 '23 02:02

mrpatg


2 Answers

There are multiple bugs in there. It should be

foreach (...
    if ($i++ < $o) continue;
    if ($i > $o + $limit) break;
    // do your stuff here
}
like image 126
soulmerge Avatar answered Mar 12 '23 03:03

soulmerge


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
}
like image 20
David Avatar answered Mar 12 '23 02:03

David