tags:

views:

90

answers:

4

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?

+2  A: 

There are multiple bugs in there. It should be

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

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

Sabeen Malik
A: 

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
+1  A: 

Please see here: http://stackoverflow.com/questions/1679559

Stefan Gehrig