What are some alternative methods to skip a loop iteration in PHP foreach loop without using Goto?
When iterating over an array using a foreach loop in PHP, you may encounter situations where you need to skip a specific iteration based on certain conditions. One common approach to achieve this is by using the continue statement within the loop block. This statement allows you to skip the current iteration and move on to the next one without using the goto statement, which is generally considered bad practice.
// Sample array
$numbers = [1, 2, 3, 4, 5];
// Iterate over the array and skip even numbers
foreach ($numbers as $number) {
if ($number % 2 == 0) {
continue; // Skip this iteration for even numbers
}
echo $number . PHP_EOL;
}
Keywords
Related Questions
- What best practices should be followed to avoid parse errors in PHP scripts, especially related to closing curly braces?
- What are best practices for resizing images in PHP to fit specific dimensions, such as maintaining aspect ratio?
- What are the best practices for structuring PHP code to ensure successful file downloads?