In PHP, you can use the ‘if’, ‘else’, and ‘elseif’ statements to execute different code blocks based on different conditions.
In PHP, the following conditional statements are available:
- if – Executes a block of code if a condition is true.
- if…else – Executes one block of code if a condition is true, and another block of code if the condition is false.
- if…elseif…else – Allows you to specify multiple conditions and execute different code blocks depending on which condition is true.
- switch – Allows you to specify multiple conditions and execute different code blocks depending on which condition is true.
Here’s the syntax for an ‘if’ statement:
if (condition) {
// Code to execute if condition is true
}
Here’s the syntax for an ‘if…else’ statement:
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
Here’s the syntax for an ‘if…elseif…else’ statement:
if (condition1) {
// Code to execute if condition1 is true
} elseif (condition2) {
// Code to execute if condition1 is false and condition2 is true
} else {
// Code to execute if condition1 and condition2 are false
}
Here’s an example of how you can use an ‘if‘ statement:
$x = 10;
if ($x > 0) {
echo '$x is positive';
}
Here’s an example of how you can use an ‘if…else’ statement:
$x = 10;
if ($x > 0) {
echo '$x is positive';
} else {
echo '$x is not positive';
}
Here’s an example of how you can use an ‘if…elseif…else’ statement:
$x = 10;
if ($x > 0) {
echo '$x is positive';
} elseif ($x < 0) {
echo '$x is negative';
} else {
echo '$x is zero';
}
You can also nest ‘if’ statements within other ‘if’ statements to create more complex conditions.
$x = 10;
$y = 5;
if ($x > 0) {
if ($y > 0) {
echo '$x and $y are both positive';
} else {
echo '$x is positive and $y is not positive';
}
} else {
echo '$x is not positive';
}
Here is an example of how you can use a ‘switch’ statement:
$x = 10;
switch ($x) {
case 0:
echo '$x is zero';
break;
case 1:
case 2:
case 3:
echo '$x is 1, 2, or 3';
break;
default:
echo '$x is not zero, 1, 2, or 3';
}
The ‘switch’ statement is similar to a series of ‘if…elseif’ statements, but it can be easier to read and write, especially when you have many conditions to test.