Definition and Usage
- PHP Version
- 4+
The while statement consists of a condition and a code block.
It is a loop that repeatedly executes the code block while the condition is true.
The loop ends when the condition becomes false.
Additional Explanation
The while statement is a Pre-test loop that checks the condition before the code block is executed. More precisely, it checks the condition, and if the condition is met, the code block is executed.
The while statement is very useful when the number of iterations is not predetermined, allowing you to repeatedly execute a code block based on a Boolean condition.
Basic Example
$i = 1;
while ($i <= 5) {
echo $i . ' ';
$i++;
}
// Output: 1 2 3 4 5
Syntax
The while statement consists of a condition enclosed in parentheses (()) and a code block ({}).
while (condition) {
// Code block to execute
}
condition
This is the condition expression that determines whether to execute the code block ({}). It is required.
- If this condition evaluates to
true, the code block ({}) is executed. - If this condition evaluates to
false, thewhilestatement is no longer executed and terminates. - If the condition expression is omitted, a syntax error occurs.
Execution Order of the while Statement
When the while statement is executed, it follows the sequence below.
- The
conditionis evaluated. If the condition evaluates totrue, the code block ({}) is executed. However, if it evaluates tofalse, thewhilestatement is no longer executed and terminates. - If the
conditionevaluates totrue, the code block ({}) is executed. - After the code block (
{}) is executed, the process returns to the first step, where theconditionis evaluated. The subsequent steps are repeated.
Note
PHP supports an alternative syntax for the while control structure (Alternative syntax for control structures). It is also known as "colon syntax". This syntax is mainly used to improve readability when mixing HTML and PHP.
while Loop
<?php while (condition): ?>
<?php // Code block to execute ?>
<?php endwhile; ?>
<?php $i = 1; ?>
<?php while ($i <= 5): ?>
<?php
echo $i . ' ';
$i++;
?>
<?php endwhile; // // Output: 1 2 3 4 5 ?>
Usefulness of the while Statement
The while statement is very useful when the number of iterations is not predetermined and a code block ({}) needs to be repeatedly executed based on a Boolean condition.
For example, it can be used to repeatedly process data when the number of items to retrieve from a database is not predetermined.
The following example retrieves and displays a list of posts from a MySQL database. Since the number of posts stored in the database is not known in advance, the while statement is used to repeat the process until all posts are displayed.
Note!
The example code provided is a simple example for understanding how the while statement works.
Additional appropriate measures may be required to use it in production.
// Database connection settings
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create a database connection using MySQLi
$conn = new mysqli($servername, $username, $password, $dbname);
// Check the connection status
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to retrieve the list of posts
$sql = "SELECT id, title, content FROM board";
$result = $conn->query($sql);
// Process the result
if ($result) {
if ($result->num_rows > 0) {
// Use the while statement to display all posts
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - Title: " . $row["title"] . " - Content: " . $row["content"] . "<br>";
}
} else {
echo "No posts found.";
}
} else {
echo "Query error: " . $conn->error;
}
// Close the database connection
$conn->close();
This example demonstrates how the while statement can be useful for repeatedly executing code when the number of iterations is not predetermined. When retrieving and processing results from a database, the number of results is not known in advance, so it is appropriate to use the while statement to repeatedly execute the code until the condition is met.
On the other hand, the for statement is very useful when repeatedly executing code a specific number of times or over a specified range.
Things to Keep in Mind
When using the while statement, be careful not to create an infinite loop.
To control the number of iterations, consider changing the condition expression or using an increment/decrement expression as appropriate.
$i = 1;
while ($i <= 5) {
echo $i;
/* Without the increment/decrement expression in this code, an infinite loop occurs. */
//$i++;
}