Giving Your Code a Brain
So far, our PHP scripts have been simple, running from the first line to the last. But what if you want your code to perform different actions based on different conditions? This is where control structures come in. They allow your program to make decisions, giving it a basic form of intelligence.
Think about everyday logic: "If it is raining, then take an umbrella, else wear sunglasses." PHP works in a very similar way.
1. The if
Statement
The if
statement is the most basic control structure. It executes a block of code only if a specified condition is true
.
<?php
$age = 20;
// The code inside the curly braces {} will only run if $age is 18 or greater.
if ($age >= 18) {
echo "You are old enough to vote.";
}
?>
2. The if...else
Statement
What if you want to do something else when the condition is false
? The else
statement provides an alternative path.
<?php
$is_logged_in = false;
if ($is_logged_in == true) {
echo "Welcome back, user!";
} else {
echo "Please log in to continue.";
}
?>
3. The if...elseif...else
Statement
Sometimes you need to check for several different conditions. The elseif
(short for "else if") statement lets you chain multiple conditions together.
<?php
$score = 75;
if ($score >= 90) {
echo "Your grade is A.";
} elseif ($score >= 80) {
echo "Your grade is B.";
} elseif ($score >= 70) {
echo "Your grade is C.";
} else {
echo "Your grade is F.";
}
// Output: Your grade is C.
?>
PHP will check each condition from top to bottom and will execute the code for the first one that is true. If none are true, it will execute the final else
block.
4. The switch
Statement
A switch
statement is an alternative to a long if...elseif...else
chain. It is often cleaner when you need to compare a single variable against many possible values.
<?php
$favorite_color = "blue";
switch ($favorite_color) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
// The `break;` keyword is important. It stops the code from continuing to check the other cases.
?>
By combining these control structures with the operators you learned in the previous lesson, you can now write programs that react and adapt to different data and inputs. In the next lesson, we'll learn how to organize our code into reusable blocks called functions.