1. if
Statement
The if
statement executes a block of code if a specified condition is true.
Syntax:
Example:
<?php
$age = 20;
if ($age >= 18) {
echo "You are an adult.";
}
?>
In this example, if $age
is 20, which is greater than or equal to 18, the message "You are an adult." is displayed.
2. if-else
Statement
The if-else
statement executes one block of code if the condition is true and another block if the condition is false.
Syntax:
if (condition) {
} else {
}
Example:
<?php
$age = 16;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}
?>
Here, if $age
is 16, the condition is false, so "You are a minor." is displayed.
3. if-elseif-else
Statement
This statement allows you to check multiple conditions. If the first condition is false, it moves to the next condition, and so on.
Syntax:
if (condition1) {
} elseif (condition2) {
} else {
}
Example:
<?php
$score = 85;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} elseif ($score >= 70) {
echo "Grade: C";
} else {
echo "Grade: F";
}
?>
The code checks multiple conditions to determine the grade based on $score
.
4. switch
Statement
The switch
statement is used when you have multiple conditions based on the value of a single expression. It is often more readable than multiple if-elseif
statements.
Syntax:
switch (expression) {
case value1:
break;
case value2:
break;
default:
}
Example:
<?php
$day = 3;
switch ($day) {
case 1:
echo "Monday";
break;
case 2:
echo "Tuesday";
break;
case 3:
echo "Wednesday";
break;
case 4:
echo "Thursday";
break;
case 5:
echo "Friday";
break;
case 6:
echo "Saturday";
break;
case 7:
echo "Sunday";
break;
default:
echo "Invalid day";
}
?>
In this example, since $day
is 3, the code will output "Wednesday".
5. ternary
Operator
The ternary operator is a shorthand way to perform a simple if-else
check in a single line of code.
Syntax:
(condition) ? true_value : false_value;
Example:
<?php
$age = 20;
echo ($age >= 18) ? "Adult" : "Minor";
?>
Here, if $age
is 20, which is greater than or equal to 18, it outputs "Adult"; otherwise, it outputs "Minor".
6. null coalescing
Operator
The null coalescing operator (??
) is used to return the value of its left operand if it exists and is not null
; otherwise, it returns its right operand.
Syntax:
$value = $variable ?? default_value;
Example:
<?php
$username = $_GET['user'] ?? 'guest';
echo $username;
?>
If $_GET['user']
is not set, it defaults to 'guest'
.