Control Structures
If / Else / Elseif Conditional Statements in PHP
Conditional statements are used to make decisions in code, meaning to execute certain pieces of code only when
a condition is true. In PHP, the most commonly used are if, else, and
elseif.
The if Statement
It is used to check a condition. If it is true (true), the code inside will be executed.
<?php
$age = 20;
if ($age >= 18) {
echo "You are allowed to access the site.";
}
?>
The if / else Statement
If the if condition is not true, then the else branch will be executed.
<?php
$age = 15;
if ($age >= 18) {
echo "Access granted.";
} else {
echo "Access denied. You must be at least 18 years old.";
}
?>
The if / elseif / else Statement
When there are multiple possible conditions, we can use elseif to check them one by one.
In the code below, the first condition $grade >= 9 is checked. If it is true, it displays “Very
good!” and the code stops checking the others.
- If not, it moves to
elseifand checks the next condition. - If none are true, the
elsebranch is executed.
<?php
$grade = 7;
if ($grade >= 9) {
echo "Very good!";
} elseif ($grade >= 7) {
echo "Good!";
} elseif ($grade >= 5) {
echo "Sufficient.";
} else {
echo "Insufficient.";
}
?>
Practical Examples with Conditional Statements in PHP
Here are some real-life situations where we use if / else / elseif to make decisions in
applications:
Example 1: Checking User Authentication
We want to check if a user is logged in or not. If they are logged in, we display a welcome message, otherwise we ask them to log in.
<?php
$isLoggedIn = false;
if ($isLoggedIn) {
echo "Welcome to your account!";
} else {
echo "Please log in to continue.";
}
?>
Example 2: Discount Based on Age
A store offers discounts for students and seniors. We use if / elseif / else to determine the
discount applied.
<?php
$age = 70;
if ($age < 18) {
echo "You get a 20% discount (student).";
} elseif ($age >= 65) {
echo "You get a 30% discount (senior).";
} else {
echo "No discount applies.";
}
?>
Example 3: Checking Entered Password
Here we simulate checking a password entered by the user. If the password is correct, we display a success message; otherwise, we display an error.
<?php
$correctPassword = "1234";
$enteredPassword = "123";
if ($enteredPassword === $correctPassword) {
echo "Correct password! Access granted.";
} else {
echo "Incorrect password! Please try again.";
}
?>
Example 4: Grading System
Depending on the student's grade, we display an evaluation. This is a classic example for elseif.
<?php
$grade = 8;
if ($grade >= 9) {
echo "Excellent!";
} elseif ($grade >= 7) {
echo "Very good!";
} elseif ($grade >= 5) {
echo "You passed!";
} else {
echo "Unfortunately, you failed the exam.";
}
?>
The switch Statement in PHP
The switch statement is an alternative to using multiple if / elseif / else. It is
used when we want to compare a single value against multiple possible options. This makes the
code more organized and easier to read.
General Syntax of switch
The basic form looks like this:
<?php
switch (expression) {
case value1:
// code executed if expression == value1
break;
case value2:
// code executed if expression == value2
break;
case value3:
// code executed if expression == value3
break;
default:
// code executed if expression does not match any case
}
?>
Explanation:
expression- the variable or value we want to check.case- defines a possible value. If the expression is equal to that value, the corresponding code is executed.break- stops execution and “exits” theswitch. If omitted, the code “falls through” into the following cases (a behavior called fall-through).default- executed only if none of thecasevalues match (equivalent toelsein if statements).
Practical Example: Days of the Week
We want to display the day of the week based on a number (1 = Monday, 2 = Tuesday, etc.).
<?php
$day = 3;
switch ($day) {
case 1:
echo "Monday";
break;
case 2:
echo "Tuesday";
break;
case 3:
echo "Wednesday";
break;
case 4:
echo "Thursday";
break;
case 5:
echo "Friday";
break;
case 6:
echo "Saturday";
break;
case 7:
echo "Sunday";
break;
default:
echo "Invalid value! The day must be between 1 and 7.";
}
?>
Example with “fall-through” (without break)
If we don't use break, execution continues into the following cases. Sometimes this is
intentional.
<?php
$grade = 10;
switch ($grade) {
case 10:
case 9:
echo "Excellent!";
break;
case 8:
case 7:
echo "Very good!";
break;
case 6:
case 5:
echo "You passed!";
break;
default:
echo "You failed the exam.";
}
?>
Here, both grade 10 and grade 9 lead to the same result (Excellent!) without duplicating code.
Example: Dynamic Menu Generated with PHP and switch
Instead of writing the options manually in HTML, we can store them in a PHP array. This way, the code becomes more flexible and easier to update.
<?php
// Define the options in an associative array
$menu = [
1 => "View Profile",
2 => "Account Settings",
3 => "Logout"
];
?>
<!-- HTML form generated by PHP -->
<form method="post">
<label for="option">Choose an option from the menu:</label><br><br>
<select name="option" id="option">
<?php
// Automatically generate the options from the array
foreach ($menu as $key => $value) {
echo "<option value='$key'>$value</option>";
}
?>
</select><br><br>
<button type="submit">Submit</button>
</form>
<?php
// Process the user's choice
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$option = $_POST["option"];
echo "<h3>Result:</h3>";
switch ($option) {
case 1:
echo "You chose to view the profile.";
break;
case 2:
echo "You chose to modify the account settings.";
break;
case 3:
echo "The program is closing... Goodbye!";
break;
default:
echo "Invalid option.";
}
}
?>
<?php
// Define options in an associative array
$menu = [
1 => "View Profile",
2 => "Account Settings",
3 => "Logout"
];
?>
<!-- HTML form generated by PHP -->
<form method="post">
<label for="option">Choose an option from the menu:</label><br><br>
<select name="option" id="option">
<?php
// Automatically generate options from the array
foreach ($menu as $key => $value) {
echo "<option value='$key'>$value</option>";
}
?>
</select><br><br>
<button type="submit">Submit</button>
</form>
<?php
// Process user's choice
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$option = $_POST["option"];
echo "<h3>Result:</h3>";
switch ($option) {
case 1:
echo "You chose to view the profile.";
break;
case 2:
echo "You chose to modify account settings.";
break;
case 3:
echo "Exiting the program... Goodbye!";
break;
default:
echo "Invalid option.";
}
}
?>
Advantages of this method
- If you want to add a new option, you just need to add one line in the
$menuarray and it will automatically appear in the form. - The HTML code stays clean and short, even if you have many options.
- It clearly separates data (the array with options) from processing logic (the switch statement).
When to choose switch instead of if / elseif?
- When you need to check a single variable against multiple possible values.
- When the code becomes hard to follow with too many
elseifstatements. - When you want to group multiple cases that have the same result.
while loops in PHP
A while loop is used when we want to repeat a certain instruction as long as a condition is
true. Basically, PHP checks the condition at each iteration and, if the result is
true, it executes the code inside the loop. When the condition becomes false, the loop
stops.
Syntax of the while loop
while (condition) {
// code that executes as long as the condition is true
}
Practical example with while
<?php
$counter = 1;
while ($counter <= 5) {
echo "The number is: $counter <br>";
$counter++;
}
?>
Step-by-step explanation
- 1. We created a variable
$counterand assigned it the value 1. - 2. The
whileloop checks if$counter <= 5. As long as this condition is true, the code inside will run. - 3. Inside, we use
echoto display the current value of$counter. - 4. At the end, we increment the variable with
$counter++, to avoid an infinite loop. - 5. When
$counterreaches 6, the condition is no longer true and the loop stops.
Where is the while loop useful?
The while loop is useful when we don't know in advance how many iterations are needed. For
example: reading data from a file until the end, iterating through SQL query results, or waiting for an external
condition.
do...while loops in PHP
A do...while loop is similar to while, but with one important difference: the
code inside will run at least once, regardless of whether the condition is true or false. Only after
the first execution the condition is checked for the following iterations.
Syntax of the do...while loop
do {
// code that runs at least once
} while (condition);
Practical example with do...while
<?php
$counter = 6;
do {
echo "The number is: $counter <br>";
$counter++;
} while ($counter <= 5);
?>
Step-by-step explanation
- 1. We set
$counterto the value6. - 2. The
do...whileloop executes the code inside without checking the condition at the beginning, so"The number is: 6"will be displayed. - 3. After the first execution, the condition
$counter <= 5is checked. Since$counteris already 7, the condition isfalse, and the loop stops.
When do we use do...while?
It is used when we want to run the code at least once, even if the condition is not met afterward. Practical examples: displaying an interactive menu, repeatedly asking the user for input until they provide a valid value.
for loops in PHP
The for loop is one of the most commonly used in PHP. It is ideal when we know in advance
how many times we want to repeat an instruction. Unlike while or
do...while, which only check a condition, the for loop has three essential components:
Syntax of the for loop
for (initialization; condition; increment/decrement) {
// the code that repeats
}
- Initialization - sets the starting value (e.g.,
$i = 1). - Condition - the loop runs as long as this expression is true.
- Increment / Decrement - defines how the counter variable changes at each
iteration (e.g.,
$i++or$i--).
Simple practical example with for
<?php
for ($i = 1; $i <= 5; $i++) {
echo "The counter value is: $i <br>";
}
?>
Step-by-step explanation
- 1. Initialization:
$i = 1. - 2. Condition: checks if
$i <= 5. If true, the code inside executes. - 3. After each execution,
$iis incremented ($i++). - 4. The loop continues until the condition is no longer true (in our case, when
$ibecomes 6, the loop stops).
When do we use the for loop?
It is useful for clear situations where we know the exact number of iterations: displaying numbers, iterating through a fixed-length list, generating tables or repetitive structures.
foreach loops in PHP
The foreach loop is specifically designed to work with arrays and
collections. It goes through each element of an array without needing to know in advance how
many elements there are. Therefore, it is the simplest and most elegant way to iterate through lists of values.
Syntax of the foreach loop
foreach ($array as $value) {
// code that uses $value
}
foreach ($array as $key => $value) {
// code that uses $key and $value
}
- $value - represents the current element in the array.
- $key - the index or key associated with that element (optional).
Simple practical example
<?php
$fruits = ["apples", "pears", "bananas"];
foreach ($fruits as $fruit) {
echo "I like to eat $fruit <br>";
}
?>
Example with keys and values
<?php
$prices = [
"apples" => 3,
"pears" => 4,
"bananas" => 5
];
foreach ($prices as $fruit => $price) {
echo "The price for $fruit is $price lei <br>";
}
?>
Modifying elements directly in foreach
If we want to modify the elements of an array during iteration, we can use references:
<?php
$fruits = ["apples", "pears", "bananas"];
foreach ($fruits as &$fruit) {
$fruit = strtoupper($fruit); // transform each element to uppercase
}
unset($fruit); // important to avoid unexpected references
print_r($fruits);
/* Array
(
[0] => APPLES
[1] => PEARS
[2] => BANANAS
)
*/
?>
Foreach with multidimensional arrays
Traversing multidimensional arrays is done using nested foreach loops:
<?php
$users = [
["name" => "John", "age" => 28],
["name" => "Anna", "age" => 25],
];
foreach ($users as $user) {
echo "Name: ".$user['name'].", Age: ".$user['age']."<br>";
}
?>
Foreach with objects
Foreach also works with objects to iterate over their properties:
<?php
class User {
public $name;
public $email;
public function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
}
}
$user = new User("John", "john@example.com");
foreach ($user as $property => $value) {
echo "$property: $value <br>";
}
?>
Why use foreach?
It is very efficient when working with arrays or objects. Instead of using a classic for loop with
a counter, foreach makes the code simpler, more readable, and reduces the risk of errors.
Best practices for foreach
- Use references carefully and unset them after use with
unset(). - Avoid modifying the array during iteration unless necessary.
- Use keys for clarity when the array is associative or multidimensional.
foreachis preferred overforfor arrays because the code becomes cleaner and easier to maintain.
Comparing loop types in PHP
PHP offers several types of loops to repeat instructions. Choosing the right loop depends on the situation: whether we know the exact number of iterations, whether we are working with arrays, or whether we want the code to run at least once.
1. The for loop
Used when we know in advance how many repetitions are needed. It is ideal for counters or iterating over nameric ranges.
<?php
for ($i = 1; $i <= 5; $i++) {
echo "The value of i is: $i <br>";
}
?>
2. The foreach loop
Specifically designed for arrays and objects. It automatically iterates over each element without needing an explicit counter.
<?php
$fruits = ["apple", "pear", "banana"];
foreach ($fruits as $fruit) {
echo "Fruit: $fruit <br>";
}
?>
3. The while loop
Executes instructions as long as the condition is true. It is used when we do not know in advance how many iterations there will be.
<?php
$counter = 1;
while ($counter <= 5) {
echo "The number is: $counter <br>";
$counter++;
}
?>
4. The do...while loop
Similar to while, but executes the code at least once, even if the condition is
false from the start.
<?php
$counter = 6;
do {
echo "The number is: $counter <br>";
$counter++;
} while ($counter <= 5);
?>
Comparison table of loops
| Loop type | When to use | Characteristics |
|---|---|---|
for |
When we know the exact number of steps | Uses a nameric counter (initialization, condition, increment) |
foreach |
For arrays and objects | No counter needed, iterates directly over elements |
while |
When the number of iterations is unknown | Checks the condition before each execution |
do...while |
When we want the block to run at least once | The condition is checked after the first execution |
Simple form validation in PHP
Form validation is essential to ensure that the user enters correct and complete data before processing. We will create a form with name and email fields, and PHP will check if these fields are filled and if the email is valid.
HTML Form
<form method="post" action="">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="text" id="email" name="email"><br><br>
<input type="submit" value="Submit">
</form>
PHP Validation Script
<?php
// Initialize variables for errors and values
$name = $email = "";
$errorName = $errorEmail = "";
// Check if the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate name
if (empty($_POST["name"])) {
$errorName = "Name is required!";
} else {
$name = htmlspecialchars($_POST["name"]);
}
// Validate email
if (empty($_POST["email"])) {
$errorEmail = "Email is required!";
} elseif (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
$errorEmail = "Email is not valid!";
} else {
$email = htmlspecialchars($_POST["email"]);
}
// If no errors, display the data
if (empty($errorName) && empty($errorEmail)) {
echo "<p>Form submitted successfully!</p>";
echo "<p>Name: $name</p>";
echo "<p>Email: $email</p>";
}
}
?>
Displaying error messages next to fields
<form method="post" action="">
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<?php echo $name; ?>">
<span style="color:red;"><?php echo $errorName; ?></span><br><br>
<label for="email">Email:</label>
<input type="text" id="email" name="email" value="<?php echo $email; ?>">
<span style="color:red;"><?php echo $errorEmail; ?></span><br><br>
<input type="submit" value="Submit">
</form>
<?php
// Initialize variables
$name = $email = "";
$nameError = $emailError = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameError = "Name is required!";
} else {
$name = htmlspecialchars($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailError = "Email is required!";
} elseif (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
$emailError = "Invalid email format!";
} else {
$email = htmlspecialchars($_POST["email"]);
}
if (empty($nameError) && empty($emailError)) {
echo "<p>Form submitted successfully!</p>";
echo "<p>Name: $name</p>";
echo "<p>Email: $email</p>";
}
}
?>
<form method="post" action="">
<label for="name">Name:</label>
<input type="text" name="name" value="<?php echo $name; ?>">
<span style="color:red;"><?php echo $nameError; ?></span><br><br>
<label for="email">Email:</label>
<input type="text" name="email" value="<?php echo $email; ?>">
<span style="color:red;"><?php echo $emailError; ?></span><br><br>
<input type="submit" value="Submit">
</form>
Step-by-step explanation
- We use
$_SERVER["REQUEST_METHOD"]to check if the form was submitted via POST. - Each field is checked with
empty(). If it is not filled, an error message is displayed. - The email is validated using
filter_var()withFILTER_VALIDATE_EMAIL. htmlspecialchars()is used to prevent XSS attacks by converting special characters to HTML entities.- If there are no errors, the data is displayed on the page.
- Error messages are shown next to their respective fields, and the filled values remain in the inputs so they are not lost upon submission.
