Loops are fundamental in any programming language, allowing us to repeat actions and work with collections of data. Let's explore the different types of loops in PHP and see how they're commonly used.
The foreach Loop
Let's start with foreach, as it's the most commonly used loop in modern PHP, especially when working with arrays:
The for Loop
When you need more control over the iteration process, the for loop is your friend:
While and Do-While Loops
These loops continue as long as a condition is true:
}
// Do-while executes at least once do { echo $count; $count++; } while ($count < 5);
Breaking and Continuing
You can control loop execution with break and continue:
}
// Simple break example $numbers = [1, 2, 3, 4, 5]; foreach ($numbers as $number) { if ($number === 3) { break; // Stop the loop } echo $number; }
While break exists and is shown here for completeness, in modern PHP you'll often find better approaches using array functions or early returns in functions.
A Glimpse into Laravel Collections
When you start working with Laravel, you'll discover Collections, which provide a more elegant way to work with arrays. Here's a little teaser:
Here's another example showing more Collection power:
In this example, we filter out inactive users and create database entries only for active ones - all in just two lines of code. This is the power of Collections: they make complex operations readable and concise.
Collections make data manipulation more readable and maintainable. We'll explore them in detail when we get to Laravel, but it's good to understand the basic loops first as they're the foundation.