PHP decision making statements

Spread the love

As the name suggests, PHP decision-making statements are used to make decisions in programming. We can also say when there is a situation where certain conditions occur in our program when a program has to take a decision to choose any specific option, then we use decision-making statements or “conditional logic“.

We have three PHP decision making statements

1. if…else
2. elseif
3. switch

1.  if…else:

This statement is used in the case when we have to execute statements, where one condition is true and other is false.

Example:

<?php
$i = 10;
if($i < 12)
{
echo "i less than 12";
}
else
{
echo "i greater than 12";
}
?>

2. elseif:

If we want to execute statements where multiple conditions are present then we can use elseif statement.

Example:

<?php
$i = 10;
if($i == 12)
{
echo "i equals 12";
}
elseif($i < 12)
{
echo "i less than 12";
}
else
{
echo "i greater 12";
}
?>

3. Switch statement

If we want to execute certain blocks of codes with specific conditions we can use switch statements.
Using switch case we can replace if..elseif..else statement.

<?php
$i = 10;
$a = 10 + 2;
switch($i)
{
case 11:
echo "Not 12";
break;
case 10:
echo "Not 12";
break;
case 12:
echo "This is 12";
break;
default:
echo "Not 12";
}
?>

Let’s see switch in details:

<?php
switch($i)
{
case "11":
//any code
break;

default:
echo "No condition matched.";
}
?>

 

Here $i is a variable name. We have to pass a variable inside “switch()” which we want to test for certain conditions. Like here if $i is equal to 11 or 12.

case “11”: here case “11”: is used to specify a condition which checks whether the value of $i is equal to value present after “case” keyword. Here we are checking whether $i is equal to 11 or not. If condition matched then the code present after “case” will execute.

Similarly, we can as many cases as we required, with specific conditions.

 

“break” statement:

The break statement is required here. If the break is not given then PHP will check other conditions also even if it matches the first condition. break will throw out the control from switch block after matched condition code gets executed.

default:

If none of the conditions present in case statement matched then the code present after “default” block will get executed.

All the above-explained PHP decision-making statements will be used in different places in your PHP programs.


Spread the love

Leave a Comment