This site uses tracking technologies. You may opt in or opt out of the use of these technologies.

Back to PHP

PHP Control Structures: Conditionals (if, else, switch) and loops (for, while, foreach).

In PHP, control structures allow you to control the flow of your code based on certain conditions or by repeating actions multiple times.

Conditionals

1. if statement

  • The if statement executes a block of code only if a specified condition is true.

$age = 18;
if ($age >= 18) {
echo "You are an adult.";
}

2. if...else statement

  • Adds an else block that executes if the condition is false.

$age = 15;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}

3. if...elseif...else statement

  • Useful when you have multiple conditions to check.

$grade = 85;
if ($grade >= 90) {
echo "Excellent";
} elseif ($grade >= 75) {
echo "Good";
} else {
echo "Needs Improvement";
}

4. switch statement

  • The switch statement checks a variable against multiple values. It’s useful when you have many specific conditions.

$day = "Wednesday";
switch ($day) {
case "Monday":
echo "Start of the work week!";
break;
case "Wednesday":
echo "Midweek!";
break;
case "Friday":
echo "Weekend is near!";
break;
default:
echo "Just another day!";
break;
}

Loops

1. for loop

  • Repeats a block of code a specified number of times.

for ($i = 0; $i < 5; $i++) {
echo "Iteration $i<br>";
}

2. while loop

  • Repeats as long as the specified condition is true.

$i = 0;
while ($i < 5) {
echo "Iteration $i<br>";
$i++;
}

3. do...while loop

  • Similar to the while loop, but the block is executed at least once, even if the condition is false initially.

$i = 0;
do {
echo "Iteration $i<br>";
$i++;
} while ($i < 5);

4. foreach loop

  • Primarily used to iterate over arrays.

$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo "Fruit: $fruit<br>";
}

These control structures are foundational for handling data and creating logic in PHP applications.