So, you’ve learned about variables, data types, and operators—great! But what if you want your program to make decisions or repeat tasks? That’s where control flow structures come in!
Control flow helps your code think logically, just like a human making choices. Let’s dive into the awesome world of if statements, switch cases, and loops in PHP!
Conditional Statements
Conditional statements let your program decide what to do based on given conditions.
If-Else Statement
The if
statement checks if a condition is true, then executes the code inside it.
$age = 18;
if ($age >= 18) {
echo "You can vote!";
} else {
echo "Sorry, you are too young to vote.";
}
if
runs if the condition is true. else
runs if the condition is false.
Elseif Ladder
Used when there are multiple conditions.
$score = 85;
if ($score >= 90) {
echo "A+ Grade";
} elseif ($score >= 80) {
echo "A Grade";
} elseif ($score >= 70) {
echo "B Grade";
} else {
echo "You need to study more!";
}
Switch Statement
If you have too many conditions, switch
is a cleaner alternative to if-elseif-else
.
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the week!";
break;
case "Friday":
echo "Weekend is coming!";
break;
default:
echo "Just another day.";
}
case
checks multiple values. break
stops execution after a match. default
runs if no cases match.
Loops
Loops repeat code multiple times, so you don’t have to type the same thing again and again!
While Loop
Runs as long as a condition is true.
$x = 1;
while ($x <= 5) {
echo "Number: $x ";
$x++;
}
Be careful of infinite loops (if the condition never becomes false).
For Loop
Perfect when you know how many times to loop.
for ($i = 1; $i <= 5; $i++) {
echo "Number: $i ";
}
for
loops have three parts:
- Start (
$i = 1
) - Condition (
$i <= 5
) - Increment (
$i++
)
Foreach Loop
Used for looping arrays.
$colors = ["Red", "Green", "Blue"];
foreach ($colors as $color) {
echo "Color: $color ";
}
foreach
loops directly access each item in the array.
Do-While Loop
Executes at least once, even if the condition is false.
$x = 10;
do {
echo "Number: $x ";
$x++;
} while ($x <= 5);
Runs once before checking the condition.
Control structures give power to your PHP programs! Now, you can: Make decisions with if
, elseif
, else
, and switch
. Repeat tasks with loops like while
, for
, foreach
, and do-while
.
0 Comments