[php] PHP: Limit foreach() statement?

How can i limit a foreach() statement? Say i only want it to run the first 2 'eaches' or something?

This question is related to php foreach limit

The answer is


you should use the break statement

usually it's use this way

$i = 0;
foreach($data as $key => $row){
    if(++$i > 2) break;
}

on the same fashion the continue statement exists if you need to skip some items.


In PHP 5.5+, you can do

function limit($iterable, $limit) {
    foreach ($iterable as $key => $value) {
        if (!$limit--) break;
        yield $key => $value;
    }
}

foreach (limit($arr, 10) as $key => $value) {
    // do stuff
}

Generators rock.


There are many ways, one is to use a counter:

$i = 0;
foreach ($arr as $k => $v) {
    /* Do stuff */
    if (++$i == 2) break;
}

Other way would be to slice the first 2 elements, this isn't as efficient though:

foreach (array_slice($arr, 0, 2) as $k => $v) {
    /* Do stuff */
}

You could also do something like this (basically the same as the first foreach, but with for):

for ($i = 0, reset($arr); list($k,$v) = each($arr) && $i < 2; $i++) {
}

this is best solution for me :)

$i=0;
foreach() if ($i < yourlimitnumber) {

$i +=1;
}

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to foreach

Angular ForEach in Angular4/Typescript? How to use forEach in vueJs? Python foreach equivalent Get current index from foreach loop TypeScript for ... of with index / key? JavaScript: Difference between .forEach() and .map() JSON forEach get Key and Value Laravel blade check empty foreach Go to "next" iteration in JavaScript forEach loop Why is "forEach not a function" for this object?

Examples related to limit

Laravel Eloquent limit and offset How to increase Neo4j's maximum file open limit (ulimit) in Ubuntu? Pagination using MySQL LIMIT, OFFSET How to fix the "508 Resource Limit is reached" error in WordPress? How to limit the number of dropzone.js files uploaded? Google drive limit number of download How can I list (ls) the 5 last modified files in a directory? Limiting Python input strings to certain characters and lengths MySQL JOIN with LIMIT 1 on joined table MySQL - UPDATE query with LIMIT