How Would I Stop This Foreach Loop After 3 Iterations

How would I stop this foreach loop after 3 iterations?

With the break command.

You are missing a bracket though.

$i=0;
foreach($results->results as $result){
//whatever you want to do here

$i++;
if($i==3) break;
}

More info about the break command at: http://php.net/manual/en/control-structures.break.php

Update: As Kyle pointed out, if you want to break the loop it's better to use for rather than foreach. Basically you have more control of the flow and you gain readability. Note that you can only do this if the elements in the array are contiguous and indexable (as Colonel Sponsz pointed out)

The code would be:

for($i=0;$i<3;$i++){
$result = $results->results[i];
//whatever you want to do here
}

It's cleaner, it's more bug-proof (the control variables are all inside the for statement), and just reading it you know how many times it will be executed. break / continue should be avoided if possible.

Break foreach loop 3

Why loop at all then? Why not just grab the first row:

$item = $r['result']['mounts'][0];

PHP foreach loop skip first 3 items

For simplicity you could repeat the foreach statement but doing the opposite and continue on the first three items.

<?php foreach ($_productCollection as $_product): ?>
<?php
$count++; // Note that first iteration is $count = 1 not 0 here.
if($count <= 3) continue; // Skip the iteration unless 4th or above.
?>
<li class="category-row-list-item">
<a class="product-name" href="<?php echo $_product->getProductUrl() ?>">
<?php echo $this->htmlEscape($_product->getName()) ?>
</a>
</li>
<?php endforeach ?>

The keyword continue is used in loops to skip the current iteration without exiting the loop, in this case it makes PHP go directly back to the first line of the foreach-statement, thus increasing counter to 4 (since 4th, 5th and 6th is what we're after) before passing the if statement.

Commentary on the approach

I kept it coherent with your existing solution but a more clean way in this case would probably be to use the built in Collection Pagination.

If you use ->setPageSize(3) you can simply iterate the collection to get the first three products and then use ->setCurPage(2) to get the second page of three items.

I'm linking this blog post on the topic here just to give you an example of how it's used but since I don't know your comfort level in working with collections I retain my first answer based on your existing code.

Break loop after every third iteration

Instead of breaking loop, you can split array in chunks and create your HTMLString accordingly.

var arr = [1, 2, 3, 4, 5];
function getULStructure(arr) { let s = '<ul>'; arr.forEach(el => { s += '<li>' + el + '</li>'; }); s += '</ul>'; return s}
function createHTMLString(arr, count) { var _htmlString = '' while (arr.length > 0) { _htmlString += getULStructure(arr.splice(0, count)) } return _htmlString}
var _html = createHTMLString(arr, 3);document.querySelector('.content').innerHTML = _html
<div class="content"></div>

How to stop foreach loop after certain ammoung of loops from simple_html_dom php

You are not actually increasing your $counter variable, so it will always stay 0.

If you want to increase it, use something like:

if ($counter++ >= 3) break;

Although in your specific case you probably need (see the manual):

if (++$counter >= 3) break;    // first increment, return value and then compare 

break out of if and foreach

if is not a loop structure, so you cannot "break out of it".

You can, however, break out of the foreach by simply calling break. In your example it has the desired effect:

$device = "wanted";
foreach($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ( $current_device[0] == $device ) {
// found a match in the file
$nodeid = $equip->id;

// will leave the foreach loop immediately and also the if statement
break;
some_function(); // never reached!
}
another_function(); // not executed after match/break
}

Just for completeness for others who stumble upon this question looking for an answer..

break takes an optional argument, which defines how many loop structures it should break. Example:

foreach (['1','2','3'] as $a) {
echo "$a ";
foreach (['3','2','1'] as $b) {
echo "$b ";
if ($a == $b) {
break 2; // this will break both foreach loops
}
}
echo ". "; // never reached!
}
echo "!";

Resulting output:

1 3 2 1 !

Break while loop every 3 iterations

With modulus operator you can split your output every 3 iterations but you still need to check for limit values that could generate empty div blocks

<?php

$counter = 0;
$limit = 10;

print "<div>\n";

while ($counter < $limit) {
print "counter is now " . $counter . "<br>\n";

if (++$counter % 3 === 0 && $counter < $limit) {
print "</div>\n<div>\n";

}
}
print "</div>\n";

Can you 'exit' a loop in PHP?

You are looking for the break statement.

$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list(, $val) = each($arr)) {
if ($val == 'stop') {
break; /* You could also write 'break 1;' here. */
}
echo "$val<br />\n";
}


Related Topics



Leave a reply



Submit