PHP Conditional Statements
Introduction
Conditional statements in PHP are used to execute specific blocks of code based on certain conditions. These statements evaluate expressions that result in true or false. If the condition is true, the corresponding block of code is executed; if false, the block is skipped.
1. if Statement
The if statement is used to execute a block of code if a specified condition is true.
if (condition) {
// Code to be executed if condition is true
}
Example:
<?php
$age = 18;
if ($age >= 18) {
echo "You are an adult.";
}
?>
Output
2. else Statement
The else statement is used to execute an alternative block of code if the if condition is false.
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
Example:
<?php
$age = 16;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}
?>
Output
3. else if Statement
The else if statement allows you to check multiple conditions. If the first condition is false, the next else if block is checked.
if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else {
// Code if all conditions are false
}
Example:
<?php
$age = 16;
if ($age >= 18) {
echo "You are an adult.";
} else if ($age >= 13) {
echo "You are a teenager.";
} else {
echo "You are a child.";
}
?>
Output
4. switch Statement
The switch statement is an alternative to using multiple if statements, particularly when you are testing a single variable against several possible values.
switch (variable) {
case value1:
// Code to execute if variable equals value1
break;
case value2:
// Code to execute if variable equals value2
break;
default:
// Code to execute if no cases match
}
Example:
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the workweek.";
break;
case "Friday":
echo "End of the workweek.";
break;
default:
echo "Midweek day.";
}
?>
Output
5. Ternary Operator
The ternary operator is a shorthand for the if-else statement. It evaluates a condition and returns one of two values based on whether the condition is true or false.
(condition) ? value_if_true : value_if_false;
Example:
<?php
$age = 18;
echo ($age >= 18) ? "Adult" : "Minor";
?>
Output
6. Null Coalescing Operator (??)
The null coalescing operator checks if a variable is set and is not null. If the variable is not set or is null, a default value is returned.
$value = $variable ?? "default_value";
Example:
<?php
$username = $_GET['username'] ?? "Guest";
echo $username;
?>
Output
Conclusion
Conditional statements in PHP allow you to control the flow of the program by executing different blocks of code based on certain conditions. They are essential for decision-making in programming and can range from simple if statements to more complex constructs like switch and ternary operators.
Understanding these conditional structures is fundamental to writing dynamic PHP applications that can respond differently to various inputs and situations.