As with all programming languages, loops in PHP are a fundamental programming concept that allows for the execution of the same set of instructions multiple times as long as a certain condition is met. What does that mean? It means that a loop executes the same code within the loop as many times as you tell the loop to do so. Imagine you were late for your computer science class and your teacher tells you to create a program that prints the sentence 'I'm sorry I'm late' 100 times. You could do this task without a loop using a hundred lines of repetitive code or use a loop that would do this task in a snap. Then ask yourself what would happen if the teacher asked you to write a million times that you were sorry. Even that, a single loop would handle with ease.
That's why loops are useful and one of the most important programming rules is to avoid any repetition of code, and loops are perfect for that job. There are several types of loops in PHP, each with specific characteristics and uses. The most common types of loops are described below:
- while loop - A while loop continues to execute as long as a specified condition evaluates to true. Once the condition becomes false, the loop terminates. This is useful when you don't know beforehand how many times the loop will iterate.
- do-while loop - A do-while loop is similar to a while loop, but the difference is that the code inside the loop will always execute at least once, regardless of whether the condition is true or false.
- for loop - A for loop is typically used when you know in advance how many times you want to execute a block of code. It consists of three parts: initialization, condition, and increment/decrement.
- foreach loop - A foreach loop is used to iterate over the elements of an array. Each element in the array is passed through the loop, making it easier to work with arrays.
Loops in PHP provide flexibility and the ability to execute code repeatedly without having to write the same lines multiple times. Understanding the different types of loops is crucial for writing efficient PHP code. Choosing the right loop depends on the specific task and desired behavior. In general, the for loop is used when you know in advance how many times you want a block of code to execute, while while and do-while loops are used when the condition for continuing the loop depends on other factors. The foreach loop is ideal for iterating over collections. PHP loops are a key tool in programming because they allow you to repeat certain operations in an efficient manner. In practice, loops solve numerous real-world problems that often arise in web applications. Here are some concrete examples and problems that PHP loops solve:
- When working with arrays or databases, it's often necessary to iterate through a large number of entries. Loops allow you to process each entry without repeating the same code. For example, when you have an array of products from a database and you want to display them to users on a webpage.
- When you need to perform a repetitive task for different users or entries, loops enable automation. For instance, sending an email to each user in a database.
- Loops are frequently used to dynamically generate HTML code, such as tables, lists, menus, product cards, etc. For example, when you need to create a table with a list of users and their information.
- Loops are often used to validate and process data from forms, especially when you have multiple inputs that require similar logic. For instance, when you need to validate a set of inputs from a form, such as email addresses, phone numbers, and names.
- When working with files or databases, you often need to iterate through rows or records. For example, reading a file line by line and displaying the content on a webpage.
- And so on.
In any case, using loops in PHP programming is common,
and it's essential that you can determine and know which loop to use in a given
situation. The loops you create for your specific needs will definitely define
how good a programmer you are. Let's now move on to the practical part, and in
the following sections, you'll see for yourself how easy coding with loops is
and how much you can gain from them.
From Theory to PHP Practice: The while Loop in a Practical Example
In this lesson, we'll create a webpage that converts seconds into a more readable format of hours, minutes, and seconds. Think of it like having three digital counters: one for seconds, one for minutes, and one for hours. When the seconds counter reaches 60, its value 'overflows' into the minutes counter, and so on. In programming, we can easily simulate this behavior using a while loop. Let's dive into our PHP tutorial.
manuel@manuel-virtual-machine:~$
sudo apt-get update
manuel@manuel-virtual-machine:~$
sudo apt-get upgrade
manuel@manuel-virtual-machine:~$
clear
manuel@manuel-virtual-machine:~$
cd /opt/lampp
manuel@manuel-virtual-machine:~$
ls
manuel@manuel-virtual-machine:/opt/lampp$
sudo ./manager-linux-x64.run
<?php
$title = 'PHP Tutorial';
require_once 'includes/header.php';
?>
<h2 class="bg-primary text-light text-center py-3">Contents</h2>
<div class="container">
<div>
<h2><font color="seagreen">Lessons</font></h2>
You can now create a new file called lesson06.php and enter the following HTML and PHP code.
<?php
// Sets the page title
$title = 'Lesson 6';
// Includes the header title
require_once '../includes/header.php';
?>
<h2 class="bg-primary text-light text-center py-3">
Lesson 6. - The while Loop
</h2>
<div class="container">
<h4>Convert seconds to H:M:S</h4>
<form method="post">
<label for="seconds">Enter number of seconds:</label>
<input type="number" id="seconds" name="seconds" min="0" max="86400" oninput="validateInput(this)">
<input type="submit" value="Convert">
</form>
<!-- JavaScript validation the HTML number control -->
<script>
function validateInput(input) {
if (input.value < 0 || input.value > 86400) {
alert("Please enter a
number from 0 to 86400.");
input.value = ""; // Clear the field if the
entry is incorrect
}
}
</script>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$totalSeconds = intval($_POST['seconds']);
if ($totalSeconds < 0 || $totalSeconds > 86400) {
echo "Invalid entry.
Please enter a number from 0 to 86400.";
} else {
$seconds = $totalSeconds;
$minutes = 0;
$hours = 0;
while ($seconds > 59) {
$seconds -= 60;
$minutes++;
if ($minutes > 59) {
$minutes -= 60;
$hours++;
}
}
echo "<p>{$totalSeconds} seconds is equal to {$hours} hours, {$minutes} minutes, and {$seconds} seconds.</p>";
}
}
?>
<!-- footer -->
<?php require_once '../includes/footer.php'; ?>
When you run this website, the result will be as in the following image.
Understanding the do-while Loop: A PHP Example
A classic use case for do-while loops is in console applications where a menu needs to be displayed at least once. This guarantees the menu is shown, even if the user's input isn't valid immediately. However, in web applications, we often have more control over the initial display. For our PHP example, we'll create a web page that takes a number from 0 to 9 and displays the numbers counting down from that number. While a while loop could also achieve this, a do-while loop ensures that the input number is always displayed, even if it's incorrect. Click on index.php, then in the code editor panel, modify the following part of the code.
<?php
$title = 'PHP Tutorial';
require_once 'includes/header.php';
?>
<h2 class="bg-primary text-light text-center py-3">Contents</h2>
<div class="container">
<div>
<h2><font color="seagreen">Lessons</font></h2>
<ul>
<li><a href="lessons/lesson01.php">
Lesson 1. - The text printing and comments
</a></li>
<li><a href="lessons/lesson02.php">
Lesson 2. - Variables and data types
</a></li>
<li><a href="lessons/lesson03.php">
Lesson 3. - Operators
</a></li>
<li><a href="lessons/lesson04.php">
Lesson 4. - Conditional Statement if-else
</a></li>
<li><a href="lessons/lesson05.php">
Lesson 5. - Conditional Statement switch-case
</a></li>
<li><a href="lessons/lesson06.php">
Lesson 6. - The while Loop
</a></li>
<li><a href="lessons/lesson07.php">
Lesson 7. - The do-while Loop
</a></li>
</ul>
</div>
</div>
<!-- footer -->
<?php require_once 'includes/footer.php'; ?>
You can now create a new file called lesson07.php and enter the following HTML and PHP code.
<?php
// Sets the page title
$title = 'Lesson 7';
// Includes the header title
require_once '../includes/header.php';
?>
<h2 class="bg-primary text-light text-center py-3">
Lesson 7. - The do-while Loop
</h2>
<div class="container">
<h4>Enter numbers from 0 to 9.</h4>
<form method="post">
<label for="number">Enter a number:</label>
<input type="number" id="number" name="number" min="0" max="9" oninput="validateInput(this)">
<input type="submit" value="Show">
</form>
<!-- JavaScript validation the HTML number control -->
<script>
function validateInput(input) {
if (input.value < 0 || input.value > 9) {
alert("Please enter a
number from 0 to 9.");
input.value = ""; // Clear the field if the
entry is incorrect
}
}
</script>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$number = intval($_POST['number']);
if ($number < 0 || $number > 9) {
echo "Invalid entry.
Please enter a number from 0 to 9.";
} else {
echo "<p>Numbers
backwards from $number:</p>";
// Display numbers
echo $number . " ";
$number--;
} while ($number >= 0);
}
<!-- footer -->
<?php require_once '../includes/footer.php'; ?>
We've assumed you're familiar with HTML and PHP. But you might be wondering why we've incorporated JavaScript validation into our PHP example. The answer lies in the importance of robust security in real-world applications. In this example, we've demonstrated a multi-layered approach to validation. First, we have HTML-based validation. However, this is triggered only when the user submits the form. To provide immediate feedback, we've added JavaScript validation that runs as the user types. Finally, and most importantly, we have server-side validation in PHP. This ensures that even if a user manages to bypass the client-side checks, their input will be sanitized before being processed by the application. When you run this website, the result will be as in the following image.
The for loop is a popular choice for numerical and financial tasks, but it requires a predetermined number of iterations. In this example, we'll demonstrate how to make the for loop more flexible by asking the user for input. We'll use it to print a specified number of asterisks, showcasing its versatility. Click on index.php, then in the code editor panel, modify the following part of the code.
<?php
$title = 'PHP Tutorial';
require_once 'includes/header.php';
?>
<h2 class="bg-primary text-light text-center py-3">Contents</h2>
<div class="container">
<div>
<h2><font color="seagreen">Lessons</font></h2>
<ul>
<li><a href="lessons/lesson01.php">
Lesson 1. - The text printing and comments
</a></li>
<li><a href="lessons/lesson02.php">
Lesson 2. - Variables and data types
</a></li>
<li><a href="lessons/lesson03.php">
Lesson 3. - Operators
</a></li>
<li><a href="lessons/lesson04.php">
Lesson 4. - Conditional Statement if-else
</a></li>
<li><a href="lessons/lesson05.php">
Lesson 5. - Conditional Statement switch-case
</a></li>
<li><a href="lessons/lesson06.php">
Lesson 6. - The while Loop
</a></li>
</div>
</div>
<!-- footer -->
<?php require_once 'includes/footer.php'; ?>
You can now create a new file called lesson08.php and enter the following HTML and PHP code.
<?php
// Sets the page title
$title = 'Lesson 8';
// Includes the header title
require_once '../includes/header.php';
?>
<h2 class="bg-primary text-light text-center py-3">
Lesson 8. - The for Loop
</h2>
<div class="container">
<h4>Enter numbers from 1 to 50.</h4>
<form method="post">
<label for="number">Enter a number:</label>
<input type="number" id="number" name="number" min="1" max="50" oninput="validateInput(this)">
<input type="submit" value="Show">
</form>
<!-- JavaScript validation the HTML number control -->
<script>
function validateInput(input) {
if (input.value < 1 || input.value > 50) {
alert("Please enter a
number from 1 to 50.");
input.value = ""; // Clear the field if the
entry is incorrect
}
}
</script>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$number = intval($_POST['number']);
if ($number < 1 || $number > 50) {
echo "Invalid entry.
Please enter a number from 1 to 50.";
} else {
echo "<p>Display $number stars:</p>";
for ($i = 1; $i <= $number; $i++) {
echo "*";
}
echo "</p>";
}
}
?>
<!-- footer -->
<?php require_once '../includes/footer.php'; ?>
The PHP code above employs a for loop to generate a series of asterisks. The loop begins by initializing a counter variable to 1. It then iterates as long as the counter is less than or equal to a user-specified value. During each iteration, an asterisk is printed to the output, and the counter is incremented. For instance, if the user inputs 43, the loop will output forty-three asterisks. When you run this website, the result will be as in the following image.
You can see how this whole process looks like in the following video, too.
First Steps: Introduction to PHP foreach Loop
Remember, foreach loops are usually used with lists of things, like arrays. We'll learn more about arrays later, but for now, let's use a simple example with a string. A string is just a series of letters, but foreach loop can still work with it. Imagine a user types a word into a box on a webpage. We can use foreach loop to look at each letter in that word and find its number value. This is useful for making word games, even though you'd normally use foreach loop with arrays for those. Click on index.php, then in the code editor panel, modify the following part of the code.
<?php
$title = 'PHP Tutorial';
require_once 'includes/header.php';
?>
<h2 class="bg-primary text-light text-center py-3">Contents</h2>
<div class="container">
<div>
<h2><font color="seagreen">Lessons</font></h2>
<ul>
<li><a href="lessons/lesson01.php">
Lesson 1. - The text printing and comments
</a></li>
<li><a href="lessons/lesson02.php">
Lesson 2. - Variables and data types
</a></li>
<li><a href="lessons/lesson03.php">
Lesson 3. - Operators
</a></li>
<li><a href="lessons/lesson04.php">
Lesson 4. - Conditional Statement if-else
</a></li>
<li><a href="lessons/lesson05.php">
Lesson 5. - Conditional Statement switch-case
</a></li>
<li><a href="lessons/lesson06.php">
Lesson 6. - The while Loop
</a></li>
<li><a href="lessons/lesson07.php">
Lesson 7. - The do-while Loop
</a></li>
<li><a href="lessons/lesson08.php">
Lesson 8. - The for Loop
</a></li>
<li><a href="lessons/lesson09.php">
Lesson 9. - The foreach Loop
</a></li>
</ul>
</div>
</div>
<!-- footer -->
<?php require_once 'includes/footer.php'; ?>
You can now create a new file called lesson09.php and enter the following HTML and PHP code.
<?php
// Sets the page title
$title = 'Lesson 9';
// Includes the header
title
require_once '../includes/header.php';
?>
<h2 class="bg-primary text-light
text-center py-3">
Lesson 8. - The foreach Loop
</h2>
<div class="container">
<h4>Print characters from a string.</h4>
<form method="post">
<label for="text">Enter a word:</label>
<input type="text" name="text" id="text">
<button type="submit">Show</button>
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$text = $_POST['text'];
$counter = 1;
foreach (str_split($text) as $sign) {
echo $counter . ". " . $sign . "<br>";
$counter++;
}
}
?>
<!-- footer -->
<?php require_once '../includes/footer.php'; ?>
When you run this website, the result will be as in the following image.
You can see how this whole process looks like in the
following video, too.
Preventing PHP Infinite Loops: Best Practices
A PHP infinite loop is a loop that keeps going forever. This can cause problems for your website. These loops often happen in while, for, and do-while loops.
Example of an infinite loop in PHP:
// Example of an infinite loop
while (true) {
// Some code that never changes the loop condition
echo "This loop will
never end.\n";
To avoid them:
- Make sure the loop has a way to stop.
- Don't use while (true) without a way to break out.
- Check your code for any mistakes in how you're controlling the loop.
No comments:
Post a Comment