The if statement
The if statement is used to execute a block of code only if a specified condition is true. Here is the basic syntax:
if (condition) {
// code to be executed if the condition is true
}
Example:
$age = 18;
if ($age >= 18) {
echo "You are eligible to vote.";
}
The if...else Statement
The if...else statement is used to execute a block of code if the condition is true, and another block of code if the condition is false. Here is the basic syntax:
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
Example:
$age = 17;
if ($age >= 18) {
echo "You are eligible to vote.";
} else {
echo "You are not eligible to vote yet.";
}
The if...elseif...else statement
The if...elseif...else statement is used to execute different blocks of code for different conditions. Here is the basic syntax:
if (condition1) {
// code to be executed if condition1 is true
} elseif (condition2) {
// code to be executed if condition2 is true and condition1 is false
} else {
// code to be executed if all conditions are false
}
Example:
$age = 20;
if ($age < 13) {
echo "You are a child.";
} elseif ($age >= 13 && $age < 18) {
echo "You are a teenager.";
} else {
echo "You are an adult.";
}
The switch statement:
The switch statement is used to perform different actions based on different conditions. It is often used as an alternative to if...elseif...else statements. Here is the basic syntax:
switch (n) {
case label1:
// code to be executed if n = label1
break;
case label2:
// code to be executed if n = label2
break;
default:
// code to be executed if n is different from all labels
}
Example:
$day = "Monday";
switch ($day) {
case "Monday":
echo "Today is Monday.";
break;
case "Tuesday":
echo "Today is Tuesday.";
break;
default:
echo "It's another day of the week.";
}