Introduction:
Welcome to our in-depth guide on PHP loops, a fundamental aspect of server-side scripting. Whether you’re a novice web developer or looking to enhance your PHP skills, this lesson will provide a solid foundation in understanding and implementing different types of loops in PHP.
PHP (Hypertext Preprocessor) is a popular server-side scripting language, and it provides several types of loops for iterating through arrays, traversing data structures, or executing a block of code repeatedly. Here are the main types of loops in PHP:
The for loop is used when you know in advance how many times you want to execute a block of code.
<?php for ($i = 0; $i < 5; $i++) { echo $i . "<br>"; } ?>
The while loop is used when you want to execute a block of code as long as a condition is true.
<?php $i = 0; while ($i < 5) { echo $i . "<br>"; $i++; } ?>
The do-while loop is similar to the while loop, but it ensures that the block of code is executed at least once, even if the condition is false.
<?php $i = 0; do { echo $i . "<br>"; $i++; } while ($i < 5); ?>
The foreach loop is specifically designed for iterating over arrays.
<?php $colors = array("red", "green", "blue"); foreach ($colors as $color) { echo $color . "<br>"; } ?>
You can use break to exit a loop prematurely and continue to skip the rest of the code inside the loop and move to the next iteration.
<?php for ($i = 0; $i < 10; $i++) { if ($i == 5) { break; // exit the loop when $i equals 5 } echo $i . "<br>"; } ?> <?php for ($i = 0; $i < 10; $i++) { if ($i % 2 == 0) { continue; // skip even numbers } echo $i . "<br>"; } ?>
These are the basic loop constructs in PHP. Depending on the situation, you can choose the appropriate loop to achieve your desired functionality.
A Complete code example in html with explanation
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PHP Loops Example</title> </head> <body> <h1>PHP Loops Example</h1> <h2>For Loop - List of Numbers:</h2> <?php // Using a for loop to generate a list of numbers echo "<ul>"; for ($i = 1; $i <= 5; $i++) { echo "<li>$i</li>"; } echo "</ul>"; ?> <h2>While Loop - Countdown:</h2> <?php // Using a while loop to display a countdown $countdown = 3; while ($countdown > 0) { echo "$countdown... "; $countdown--; } echo "Blast off!"; ?> <h2>Do-While Loop - Welcome Message:</h2> <?php // Using a do-while loop to show a message at least once $displayMessage = false; do { echo "<p>Welcome to our website!</p>"; } while ($displayMessage); ?> <h2>Foreach Loop - List of Colors:</h2> <?php // Using a foreach loop to iterate through an array of colors $colors = array("red", "green", "blue"); echo "<ul>"; foreach ($colors as $color) { echo "<li>$color</li>"; } echo "</ul>"; ?> </body> </html>
Explanation:
You can save this code in a file with a .php extension and run it on a server with PHP support to see the output.
Another example
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Multiplication Table Generator</title> </head> <body> <h1>Multiplication Table Generator</h1> <form method="post" action=""> <label for="number">Enter a number:</label> <input type="number" name="number" required> <button type="submit">Generate Table</button> </form> <?php // Check if the form is submitted if ($_SERVER["REQUEST_METHOD"] === "POST") { // Retrieve the input $number = $_POST["number"]; // Validate the input if (!is_numeric($number)) { echo "<p>Please enter a valid number.</p>"; } else { // Display the multiplication table using a for loop echo "<h2>Multiplication Table for $number:</h2>"; echo "<table border='1'>"; for ($i = 1; $i <= 10; $i++) { echo "<tr><td>$number x $i</td><td>=</td><td>" . ($number * $i) . "</td></tr>"; } echo "</table>"; } } ?> </body> </html>
Explanation:
Save this code in a file with a .php extension and run it on a server with PHP support. Enter a number in the form, submit it, and you’ll see the multiplication table for that number.
Create a file named multiplication_app.php with the following code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Multiplication Table Generator</title> <style> table { border-collapse: collapse; width: 50%; margin-top: 20px; } table, th, td { border: 1px solid black; text-align: center; padding: 10px; } </style> </head> <body> <h1>Multiplication Table Generator</h1> <form method="post" action=""> <label for="number">Enter a number:</label> <input type="number" name="number" required> <button type="submit">Generate Table</button> </form> <?php // Check if the form is submitted if ($_SERVER["REQUEST_METHOD"] === "POST") { // Retrieve the input $number = $_POST["number"]; // Validate the input if (!is_numeric($number)) { echo "<p>Please enter a valid number.</p>"; } else { // Display the multiplication table using a for loop echo "<h2>Multiplication Table for $number:</h2>"; echo "<table>"; echo "<tr><th>Multiplier</th><th>Result</th></tr>"; for ($i = 1; $i <= 10; $i++) { echo "<tr><td>$number x $i</td><td>" . ($number * $i) . "</td></tr>"; } echo "</table>"; } } ?> </body> </html>
Here’s how the application works:
Save the file, and you can run it on a server with PHP support. Open the file in a web browser, enter a number, and you’ll see the corresponding multiplication table.
Another application:create a basic to-do list application
Create a file named todo_app.php with the following code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Simple To-Do List</title> </head> <body> <h1>Simple To-Do List</h1> <?php // Initialize the task array $tasks = []; // Check if the form is submitted if ($_SERVER["REQUEST_METHOD"] === "POST") { // Add a new task if (!empty($_POST["task"])) { $newTask = $_POST["task"]; $tasks[] = $newTask; } // Delete a task if (isset($_POST["delete"])) { $taskIndex = $_POST["delete"]; if (isset($tasks[$taskIndex])) { unset($tasks[$taskIndex]); } } } ?> <h2>Add a Task</h2> <form method="post" action=""> <label for="task">Task:</label> <input type="text" name="task" required> <button type="submit">Add Task</button> </form> <h2>Task List</h2> <?php // Display the task list if (empty($tasks)) { echo "<p>No tasks added yet.</p>"; } else { echo "<ul>"; foreach ($tasks as $index => $task) { echo "<li>$task <form style='display:inline;' method='post' action=''><input type='hidden' name='delete' value='$index'><button type='submit'>Delete</button></form></li>"; } echo "</ul>"; } ?> </body> </html>
Here’s how the to-do list application works:
A. To execute a block of code repeatedly as long as a condition is true.
B. To generate a list of numbers or iterate through an array a specific number of times.
C. To execute a block of code at least once, even if the condition is false.
D. To skip the rest of the code inside the loop and move to the next iteration.
A. foreach is used for executing a block of code repeatedly.
B. foreach is specifically designed for iterating through arrays.
C. for is used for iterating through arrays.
D. for is used when you don’t know in advance how many times the loop should run.
A. Skips the rest of the code inside the loop and moves to the next iteration.
B. Exits the loop prematurely.
C. Repeats the loop from the beginning.
D. None of the above.
A. <table>
B. <list>
C. <ul>
D. <div>
A. By clicking the “Delete” button next to the task.
B. By submitting the form with an empty task input.
C. By clicking the “Add Task” button.
D. By refreshing the entire page.
A. To execute a block of code repeatedly as long as a condition is true.
B. To iterate through an array of values.
C. To generate a list of numbers.
D. To exit the loop prematurely.
A. To check if the form has been submitted.
B. To check if a task has been added.
C. To check if a task deletion request is set in the form.
D. To check if the task list is empty.
A. do-while always executes the loop at least once, even if the condition is false.
B. while always executes the loop at least once, even if the condition is false.
C. There is no difference; they are interchangeable.
D. do-while is used for iterating through arrays.
A. Change $i++ to $i += 2 in the for loop.
B. Add a conditional statement inside the for loop to check if $i is even.
C. Use a while loop instead of a for loop.
D. There is no way to achieve this with loops.
A. To make the form visible on the webpage.
B. To hide the form from the .
C. To ensure the form is displayed on the same line as the corresponding task.
D. To style the form with a specific color.