Welcome to our comprehensive guide on PHP if-else Statements! In this lesson, we'll learn about making decisions in PHP using if-else statements. By the end, you'll be able to write confidently and control the flow of your code. π
If-else statements in PHP are used to make decisions in your code. They allow you to execute different blocks of code based on conditions you define. Let's start by understanding the basic if statement.
if (condition) {
// code to execute if condition is true
}In the above example, replace condition with a boolean expression, such as:
if (5 > 3) {
echo "5 is greater than 3";
}When you run the code, it will output: 5 is greater than 3. This is because the condition 5 > 3 is true, so the code inside the if block is executed.
Now let's add an else statement to handle cases when the condition is false.
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}For example:
if (5 < 3) {
echo "5 is less than 3";
} else {
echo "5 is not less than 3";
}The output will be: 5 is not less than 3, because the condition 5 < 3 is false, so the code inside the else block is executed.
When you have multiple conditions to check, you can use an if-else ladder:
if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if condition1 is false and condition2 is true
} else if (condition3) {
// code to execute if condition1 and condition2 are false and condition3 is true
} else {
// code to execute if all conditions are false
}Here's an example:
$number = 10;
if ($number > 15) {
echo "The number is greater than 15";
} else if ($number > 10) {
echo "The number is between 10 and 15";
} else if ($number > 5) {
echo "The number is between 5 and 10";
} else {
echo "The number is less than 5";
}The output will be: The number is between 10 and 15.
Which PHP statement allows you to make decisions in your code?
Which of the following blocks of code handles the case when the condition is false?
What does an if-else ladder do?