In PHP, decision making refers to the process of controlling the flow of your program based on certain conditions. PHP provides several conditional statements to make decisions in your code, including if
, else
, elseif
, and switch
. These statements help you execute different blocks of code depending on whether specific conditions are met.
Here are some code examples illustrating decision making in PHP:
1. The if
statement:
The if
statement is the most basic form of decision making in PHP. It checks a condition and executes a block of code if the condition is true.
$age = 18;
if ($age >= 18) {
echo "You are an adult.";
}
In this example, the message “You are an adult.” will be printed if the value of $age
is greater than or equal to 18.
2. The else
statement:
The else
statement allows you to execute an alternative block of code if the condition in the if
statement is false.
$age = 16;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are not an adult.";
}
In this example, the message “You are not an adult.” will be printed if the value of $age
is less than 18.
3. The elseif
statement:
The elseif
statement allows you to test multiple conditions and execute the first block of code whose condition is true.
$grade = 85;
if ($grade >= 90) {
echo "You got an A.";
} elseif ($grade >= 80) {
echo "You got a B.";
} elseif ($grade >= 70) {
echo "You got a C.";
} else {
echo "You got a D or below.";
}
In this example, the message “You got a B.” will be printed since the value of $grade
is 85.
4. The switch
statement:
The switch
statement is an alternative to using multiple if
and elseif
statements when you need to test a variable against multiple values.
$weekday = "Friday";
switch ($weekday) {
case "Monday":
echo "Today is Monday.";
break;
case "Tuesday":
echo "Today is Tuesday.";
break;
case "Wednesday":
echo "Today is Wednesday.";
break;
case "Thursday":
echo "Today is Thursday.";
break;
case "Friday":
echo "Today is Friday.";
break;
case "Saturday":
echo "Today is Saturday.";
break;
case "Sunday":
echo "Today is Sunday.";
break;
default:
echo "Invalid weekday.";
}
In this example, the message “Today is Friday.” will be printed since the value of $weekday
is “Friday”.
These are the basic decision-making statements in PHP, which allow you to control the flow of your program and execute different blocks of code based on specific conditions.