Why conditional statements are used in PHP?

You are currently viewing Why conditional statements are used in PHP?

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:

				
					<?php
$x = 10;
if ($x == 10) {
  echo "Variable x 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:

				
					<?php
$age = 20;
if ($age >= 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:

				
					<?php
$num = -2;
if ($num > 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:

				
					<?php
$color = "black";
switch ($color) {
  case "red":
    echo "Your favorite color is red";
    break;
  case "black":
    echo "Your favorite color is black";
    break;
  case "green":
    echo "Your favorite color is green";
    break;
  default:
    echo "Your favorite color is neither red, black, nor green";
}
?>

				
			
				
					Output :-
Your favorite color is black

				
			

Leave a Reply