Tuesday, July 05, 2011

PHP - Limit A Loop - FOREACH,WHILE etc

If you just want to loop through (for example) 2 iterations of a loop, rather than returning the whole set of data, you can insert a break clause to limit the number of times the data is looped through and so limit the results to two iterations.

$i = 0;

foreach($vars as $var){

//code to run


if(++$i > 2) break;

}

No comments: