How can a foreach loop in PHP be terminated after a specific number of iterations?
To terminate a foreach loop in PHP after a specific number of iterations, you can use a counter variable to track the number of iterations and break out of the loop when the desired number is reached. Inside the loop, you can increment the counter variable and use an if statement to check if it has reached the limit to break out of the loop.
$items = [1, 2, 3, 4, 5];
$limit = 3;
$counter = 0;
foreach ($items as $item) {
echo $item . "\n";
$counter++;
if ($counter == $limit) {
break;
}
}
Related questions
-
multilingual PHP websites resources
-
foreach PHP JSON
-
syntax errors infinite loops off-by-one errors