Lesson 2
PHP Loops and Iterations Basics
Topic Overview

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

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
1<?php 2 3$friends = array("Alice", "Bob", "Charlie", "Daniel"); 4 5foreach ($friends as $friendName) { 6 // For each friendName, print the greeting 7 echo "Hello, $friendName! Nice to meet you.\n"; 8}

Loops enable us to execute repetitive sequences automatically and efficiently.

For Loop in PHP

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:

  1. Initialization: This is where you set up the loop variable. It's executed once when the loop begins.
  2. 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.
  3. Iteration: This is where you update the loop variable. This statement executes after the loop body and right before the next condition check.
  4. Loop Body: The block of code to be executed in each loop.

Let's print a range of numbers using a for loop:

php
1for ($num = 0; $num < 5; $num++) { 2 // This line prints numbers from 0 to 4 3 echo $num . "\n"; 4}

In each cycle of the loop, the variable ($num) is updated before executing the code inside the block.

Foreach Loop in PHP

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
1<?php 2 3$fruits = array("apple", "banana", "cherry"); 4 5// `$fruit` stands for each fruit in the `$fruits` array 6foreach ($fruits as $fruit) { 7 echo $fruit . "\n"; // print each fruit 8}

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
1<?php 2 3$word = "hello"; 4for ($i = 0; $i < strlen($word); $i++) { 5 echo $word[$i] . "\n"; // print each character from 'hello' 6}

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.

While Loop in PHP

While loops in PHP continuously execute their content until a particular condition becomes false. Here's a simple example:

php
1<?php 2 3$num = 0; 4// The loop keeps running until $num is no longer less than 5 5while ($num < 5) { 6 echo $num . "\n"; 7 // Increase num by 1 at the end of each iteration 8 $num++; 9}

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

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
1<?php 2 3$numbers = array(1, 2, 3, 4, 5); 4 5$total = 0; 6// `$num` is each number in `$numbers` 7foreach ($numbers as $num) { 8 $total += $num; // Add each number in the array 9} 10echo $total . "\n"; // print the total sum
php
1<?php 2 3$text = "hello"; 4$vowelCount = 0; 5// `ch` is each character in `text` 6for ($i = 0; $i < strlen($text); $i++) { 7 $ch = $text[$i]; 8 // If a vowel letter is found, increment the count 9 if ($ch == 'a' || $ch == 'e' || $ch == 'i' || $ch == 'o' || $ch == 'u') { 10 $vowelCount++; 11 } 12} 13echo $vowelCount . "\n"; // print the count of vowels
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!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.