Learning Objectives – after this chapter you will be able to:
- Use
if,if…elseandif…elseif…elseto choose between blocks of code. - Use the
switchstatement and understand whybreakis needed. - Write nested conditions and use the PHP 8
matchexpression. - Use the alternative (colon) syntax inside HTML templates.
Making Decisions
Very often when you write code you want to perform different actions for different decisions. Conditional statements let you do this. In PHP we have the following conditional statements:
- if – execute some code only if a specified condition is true.
- if…else – execute some code if a condition is true and other code if it is false.
- if…elseif…else – select one of several blocks of code to be executed.
- switch – select one of many blocks of code to be executed.
- match (PHP 8) – return one of many values depending on a value.
The if Statement
Use the if statement to execute some code only if a specified condition is true.
if (condition) {
code to be executed if condition is true;
}The following example outputs "Have a nice weekend!" if the current day is Friday. The function date("D") returns the three-letter name of today (Mon, Tue … Sun).
<html>
<body>
<?php
$d = date("D");
echo "Today is $d.<br>";
if ($d == "Fri") echo "Have a nice weekend!";
if ($d != "Sun") echo "It is a working day.";
?>
</body>
</html>Today is Thu. It is a working day.
The if…else Statement
Use if…else to execute some code if a condition is true and another code if the condition is false.
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;<html>
<body>
<?php
$d = date("D");
if ($d == "Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
</body>
</html>Have a nice day!
If more than one line should be executed when a condition is true or false, the lines must be enclosed in curly braces:
<?php
$marks = 68;
if ($marks >= 40) {
echo "Hello!<br>";
echo "You have passed with $marks marks.<br>";
echo "See you in the next semester!";
} else {
echo "Sorry, you have failed.<br>";
echo "Please appear again.";
}
?>Hello! You have passed with 68 marks. See you in the next semester!
The if…elseif…else Statement
Use if…elseif…else to select one of several blocks of code to be executed.
if (condition1)
code to be executed if condition1 is true;
elseif (condition2)
code to be executed if condition2 is true;
else
code to be executed if all conditions are false;The following example outputs "Have a nice weekend!" on Friday, "Have a nice Sunday!" on Sunday and "Have a nice day!" otherwise:
<?php
$d = date("D");
if ($d == "Fri")
echo "Have a nice weekend!";
elseif ($d == "Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>Have a nice day!
A typical use is converting a percentage into a grade:
<?php
$per = $_GET['per'] ?? 0;
if ($per >= 75) {
$grade = "Distinction";
} elseif ($per >= 60) {
$grade = "First Division";
} elseif ($per >= 45) {
$grade = "Second Division";
} elseif ($per >= 33) {
$grade = "Third Division";
} else {
$grade = "Fail";
}
echo "Percentage: $per% — Result: $grade";
?>Percentage: 76% — Result: Distinction
Nested if
An if statement can be placed inside another if:
<?php
$age = 22;
$citizen = "Indian";
if ($age >= 18) {
if ($citizen == "Indian") {
echo "You are eligible to vote in India.";
} else {
echo "You are an adult, but not an Indian citizen.";
}
} else {
echo "You are not yet 18.";
}
?>You are eligible to vote in India.
The switch Statement
Use the switch statement to select one of many blocks of code to be executed.
switch (n) {
case label1:
code to be executed if n == label1;
break;
case label2:
code to be executed if n == label2;
break;
default:
code to be executed if n is different from all labels;
}This is how it works: first we have a single expression n (most often a variable) that is evaluated once. The value of the expression is then compared with the value of each case. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default block is used if no match is found.
<html>
<body>
<?php
$x = $_GET['x'] ?? 0;
switch ($x) {
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
}
?>
</body>
</html>Number 2
Fall-through without break
When break is missing, execution "falls through" into the following cases. This can be used deliberately to share code between cases:
<?php
$month = 4;
switch ($month) {
case 4: case 6: case 9: case 11:
$days = 30;
break;
case 2:
$days = 28;
break;
default:
$days = 31;
}
echo "Month $month has $days days.";
?>Month 4 has 30 days.
The match Expression (PHP 8)
match is a shorter and stricter relative of switch. It returns a value, compares with === (no type juggling), needs no break, and throws an UnhandledMatchError if no arm matches and there is no default.
<?php
$code = 404;
$text = match ($code) {
200 => "OK",
301, 302 => "Redirect",
404 => "Not Found",
500 => "Server Error",
default => "Unknown status",
};
echo "HTTP $code: $text";
?>HTTP 404: Not Found
Alternative Syntax for Templates
Inside HTML it is often easier to read the colon syntax – if (…):, elseif (…):, else: and endif; (similarly endswitch;, endfor;, endforeach;, endwhile;).
<?php $loggedIn = true; $user = "Asha"; ?>
<html><body>
<?php if ($loggedIn): ?>
<p>Welcome back, <?= $user ?>!</p>
<?php else: ?>
<p>Please log in.</p>
<?php endif; ?>
</body></html>Welcome back, Asha!
Key Takeaways
ifruns code when a condition is true;elseprovides the alternative;elseifchains several tests.- Use curly braces when a branch contains more than one statement – it is good practice always.
switchcompares one value against manycaselabels;breakstops fall-through;defaulthandles no match.- PHP 8
matchreturns a value, uses strict comparison and needs nobreak. - The colon syntax (
if: … endif;) keeps HTML templates readable.
Program File
Extract the ZIP into C:\xampp\htdocs. It creates the folder phpbook/ch06 used in the file labels above; open the programs at http://localhost/phpbook/… with Apache (and MySQL, where needed) started in the XAMPP Control Panel.
Question / Answer (15 questions)
MCQ Test : Check Your Understanding (5 questions)
Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.
Bibliography/References
The notes on this page are the author’s own compilation from the e-book PHP: Basics to Advance. Every program was run on Apache with PHP 8 and MariaDB, and the output shown is the real result of that run. The works listed below were consulted and are cited for attribution and further reading. Product names and trademarks belong to their respective owners.
- The PHP Group. (n.d.). PHP Manual – if. https://www.php.net/manual/en/control-structures.if.php
- The PHP Group. (n.d.). PHP Manual – switch. https://www.php.net/manual/en/control-structures.switch.php
- The PHP Group. (n.d.). PHP Manual – match. https://www.php.net/manual/en/control-structures.match.php
- The PHP Group. (n.d.). PHP Manual – Alternative syntax for control structures. https://www.php.net/manual/en/control-structures.alternative-syntax.php