Greetings, Explorer! In this lesson, we will delve into the essential tools of PHP loops. Loops in programming simplify and enhance the efficiency of repetitive tasks — much like a coffee maker brewing multiple cups with a single press, they automate the process, ensuring each cup is brewed quickly and consistently. In this lesson, we will explore the universe of looping in PHP and gain hands-on experience by applying loops to PHP arrays and strings.
Understanding Looping
For Loop in PHP
Foreach Loop in PHP
While Loop in PHP
While loops in PHP continuously execute their content until a particular condition becomes false. Here's a simple example:
<?php$num = 0;// The loop keeps running until $num is no longer less than 5while ($num < 5) { echo $num . "\n"; // Increase num by 1 at the end of each iteration $num++;}
As you can see, before each iteration, PHP checks the condition ($num < 5). If it's true, the loop continues; otherwise, the loop breaks.
Applications of Looping
Lesson Summary and Practice
Congratulations on mastering PHP loops! We've brushed up on for, foreach, and while loops and have seen how to loop over arrays and strings. Now, it's time for some beneficial practice exercises to solidify your learning. The more problems you solve, the better you'll become. Let's proceed further on our journey into the depths of programming!
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal
Imagine listening to your favorite song on repeat. That's the concept of loops in programming. For instance, we can use a foreach loop to print greetings for a group of friends.
PHP
<?php$friends = array("Alice", "Bob", "Charlie", "Daniel");foreach ($friends as $friendName) { // For each friendName, print the greeting echo "Hello, $friendName! Nice to meet you.\n";}
Loops enable us to execute repetitive sequences automatically and efficiently.
The for loop is a control flow statement that allows code to be executed repeatedly.
The structure of a for loop is typically for (initialization; condition; iteration) {loop body}, where the loop body gets executed for as long as the condition evaluates to true. After each loop, the iteration is executed, which generally updates the value of the loop control variable. Here is how it generally works:
Initialization: This is where you set up the loop variable. It's executed once when the loop begins.
Condition: This Boolean expression determines if the loop will continue or stop. If it's true, the loop continues; if it's false, the loop ends, and the flow jumps to the next statement after the loop.
Iteration: This is where you update the loop variable. This statement executes after the loop body and right before the next condition check.
Loop Body: The block of code to be executed in each loop.
Let's print a range of numbers using a for loop:
PHP
for ($num = 0; $num < 5; $num++) { // This line prints numbers from 0 to 4 echo $num . "\n";}
In each cycle of the loop, the variable ($num) is updated before executing the code inside the block.
The foreach loop is an efficient way to iterate over arrays in PHP. It allows us to work with arrays more simply and safely since it eliminates the need to manually control the array index.
PHP
<?php$fruits = array("apple", "banana", "cherry");// `$fruit` stands for each fruit in the `$fruits` arrayforeach ($fruits as $fruit) { echo $fruit . "\n"; // print each fruit}
In the above example, the $fruit variable stands for each element in the $fruits array. The loop body executes once for each item in the $fruits array, with $fruit being a reference to the current element in each iteration.
Similarly, we may loop through strings (which are essentially arrays of characters in PHP) by using string manipulation functions and for loop:
PHP
<?php$word = "hello";for ($i = 0; $i < strlen($word); $i++) { echo $word[$i] . "\n"; // print each character from 'hello'}
In the example above, we use the strlen() function to determine the length of the string word. The loop repeats for each character in the string. For each repetition, it prints the specific character, hence printing 'hello' one character at a time.
PHP
<?php$num = 0;// The loop keeps running until $num is no longer less than 5while ($num < 5) { echo $num . "\n"; // Increase num by 1 at the end of each iteration $num++;}
Loops are integral to programming. They are extensively used in various sections of a program, such as summing elements in an array and parsing through text.
PHP
<?php$numbers = array(1, 2, 3, 4, 5);$total = 0;// `$num` is each number in `$numbers`foreach ($numbers as $num) { $total += $num; // Add each number in the array}echo $total . "\n"; // print the total sum
PHP
<?php$text = "hello";$vowelCount = 0;// `ch` is each character in `text`for ($i = 0; $i < strlen($text); $i++) { $ch = $text[$i]; // If a vowel letter is found, increment the count if ($ch == 'a' || $ch == 'e' || $ch == 'i' || $ch == 'o' || $ch == 'u') { $vowelCount++; }}echo $vowelCount . "\n"; // print the count of vowels