5

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?

mrpatg
  • 10,001
  • 42
  • 110
  • 169

4 Answers4

8

There are multiple bugs in there. It should be

foreach (...
    if ($i++ < $o) continue;
    if ($i > $o + $limit) break;
    // do your stuff here
}
soulmerge
  • 73,842
  • 19
  • 118
  • 155
1

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
}
David
  • 57
  • 4
  • 1
    This suits better as a comment under soulmerge's answer, rather than an own answer. – L. Guthardt Apr 16 '18 at 10:00
  • This is not true. Since he did the `$i++` in the previous if, you have to use strictly superior, or you would get `$limit - 1` results, instead of `$limit` results. – Hexalyse Nov 28 '19 at 10:31
0
if($i == $limit+$o){break;} 

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

talha2k
  • 24,937
  • 4
  • 62
  • 81
Sabeen Malik
  • 10,816
  • 4
  • 33
  • 50
0

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

Sergey Kuznetsov
  • 8,591
  • 4
  • 25
  • 22