Why conditional statements are used in PHP?
Conditional statements are used in PHP to execute different blocks of code based on different conditions. PHP provides several types of conditional statements, including if, else, elseif and switch.
1. The ‘if’ statement is used to execute a block of code if a specified condition is true.
Here’s an example of an if statement that checks if a variable is equal to 10:
Output will be -:
Variable x is equal to 10
2. The if…else statement is used to execute one block of code if the condition is true, and another block of code if the condition is false.
Here’s an example of an if…else statement that checks person is eligible to vote or not:
= 18) {
echo "person are old enough to vote";
} else {
echo "person are not old enough to vote";
}
?>
Output:
person are old enough to vote
3. The if…elseif…else statement is used to execute different blocks of code for more than two conditions.
Here’s an example of an if…elseif…else statement that checks if a variable is greater than, less than, or equal to 0:
0) {
echo "The number is positive";
} elseif ($num < 0) {
echo "The number is negative";
} else {
echo "The number is zero";
}
?>
Output will be -:
The number is negative
4. The switch statement selects one of many blocks of code to be executed based on a specified value.
Here’s an example of a switch statement that checks the value of a variable and executes the corresponding block of code:
Output :-
Your favorite color is black