Control statements in PHP define how the program flows, allowing you to make decisions, run code repeatedly, or execute specific blocks based on conditions.
They are essential for writing dynamic, logical, and interactive PHP applications.
PHP provides several types of control statements:
- Conditional statements (if, else, elseif, switch)
- Looping statements (for, while, do…while, foreach)
- Jump statements (break, continue)
Let’s explore each of them with examples.
Conditional Control Statements
Conditional statements allow your code to take different paths based on conditions.
1. if Statement
$age = 20;
if ($age >= 18) {
echo "You are eligible to vote.";
}
2. if…else Statement
$score = 45;
if ($score >= 50) {
echo "Pass";
} else {
echo "Fail";
}
3. elseif Ladder
$marks = 75;
if ($marks >= 90) {
echo "Grade A";
} elseif ($marks >= 75) {
echo "Grade B";
} elseif ($marks >= 50) {
echo "Grade C";
} else {
echo "Grade D";
}
4. switch Statement
Useful when comparing one variable with multiple fixed values.
$day = 3;
switch ($day) {
case 1: echo "Monday"; break;
case 2: echo "Tuesday"; break;
case 3: echo "Wednesday"; break;
default: echo "Unknown day";
}
Looping Control Statements
Loops allow you to execute a block of code multiple times.
1. for Loop
Useful when you know the number of iterations.
for ($i = 1; $i <= 5; $i++) {
echo "Number: $i<br>";
}
2. while Loop
Runs as long as the condition is true.
$count = 1;
while ($count <= 3) {
echo $count . "<br>";
$count++;
}
3. do…while Loop
Executes at least once, even if the condition is false.
$k = 1;
do {
echo $k;
$k++;
} while ($k <= 3);
4. foreach Loop
Best for iterating through arrays.
$colors = ["Red", "Blue", "Green"];
foreach ($colors as $color) {
echo $color . "<br>";
}
Jump Control Statements
These statements control how loops behave.
1. break
Stops the loop immediately.
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) break;
echo $i; // Prints 1, 2
}
2. continue
Skips the current iteration.
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) continue;
echo $i . "<br>"; // Skips 3
}
Best Practices
- Use
switchinstead of multipleelseifwhen checking many fixed values. - Avoid infinite loops by ensuring conditions eventually become false.
- Prefer
foreachwhen working with arrays for cleaner code. - Use
breakandcontinuewisely to maintain readable logic.
External Reference:
🔗 https://www.php.net/manual/en/
View Other Articles About PHP:
🔗 http://savanka.com/category/learn/php/