Core PHP 10 programs with output 15 Q/A 5 MCQs

Learning Objectives – after this chapter you will be able to:

  • Use if, if…else and if…elseif…else to choose between blocks of code.
  • Use the switch statement and understand why break is needed.
  • Write nested conditions and use the PHP 8 match expression.
  • 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.

Syntax
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).

File: htdocs/phpbook/ch06/if.php
<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>
OUTPUT browser · http://localhost/phpbook/ch06/if.php
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.

Syntax
if (condition)
    code to be executed if condition is true;
else
    code to be executed if condition is false;
File: htdocs/phpbook/ch06/ifelse.php
<html>
<body>
<?php
$d = date("D");
if ($d == "Fri")
    echo "Have a nice weekend!";
else
    echo "Have a nice day!";
?>
</body>
</html>
OUTPUT browser · http://localhost/phpbook/ch06/ifelse.php
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:

File: htdocs/phpbook/ch06/ifelse2.php
<?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.";
}
?>
OUTPUT browser · http://localhost/phpbook/ch06/ifelse2.php
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.

Syntax
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:

File: htdocs/phpbook/ch06/elseif.php
<?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!";
?>
OUTPUT browser · http://localhost/phpbook/ch06/elseif.php
Have a nice day!

A typical use is converting a percentage into a grade:

File: htdocs/phpbook/ch06/grade.php
<?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";
?>
OUTPUT browser · http://localhost/phpbook/ch06/grade.php?per=76
Percentage: 76% — Result: Distinction
Nested if

An if statement can be placed inside another if:

File: htdocs/phpbook/ch06/nested.php
<?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.";
}
?>
OUTPUT browser · http://localhost/phpbook/ch06/nested.php
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.

Syntax
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.

File: htdocs/phpbook/ch06/switch.php
<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>
OUTPUT browser · http://localhost/phpbook/ch06/switch.php?x=2
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:

File: htdocs/phpbook/ch06/fallthrough.php
<?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.";
?>
OUTPUT browser · http://localhost/phpbook/ch06/fallthrough.php
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.

File: htdocs/phpbook/ch06/match.php
<?php
$code = 404;
$text = match ($code) {
    200 => "OK",
    301, 302 => "Redirect",
    404 => "Not Found",
    500 => "Server Error",
    default => "Unknown status",
};
echo "HTTP $code: $text";
?>
OUTPUT browser · http://localhost/phpbook/ch06/match.php
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;).

File: htdocs/phpbook/ch06/altsyntax.php
<?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>
OUTPUT browser · http://localhost/phpbook/ch06/altsyntax.php
Welcome back, Asha!
Key Takeaways
  • if runs code when a condition is true; else provides the alternative; elseif chains several tests.
  • Use curly braces when a branch contains more than one statement – it is good practice always.
  • switch compares one value against many case labels; break stops fall-through; default handles no match.
  • PHP 8 match returns a value, uses strict comparison and needs no break.
  • 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)

Answer : Statements that let a program take different actions depending on whether a condition is true or false: if, if…else, if…elseif…else, switch and match.

Answer : if (condition) { statements; } – the statements run only when the condition evaluates to true.

Answer : When more than one statement must be executed for a branch. Without braces only the first statement belongs to the if/else. Using braces always is a good habit.

Answer : if…else chooses between exactly two blocks. if…elseif…else tests several conditions in turn and runs the block of the first true condition, or the else block if none is true.

Answer : The three-letter textual name of the current day, from Mon to Sun.

Answer : An if statement placed inside another if or else block, used when a second decision depends on the first, e.g. checking citizenship only for people aged 18 or over.

Answer : The expression is evaluated once and its value compared with each case label. When a match is found, the statements of that case run until a break; if no case matches, the default block runs.

Answer : break ends the switch. Without it execution continues ("falls through") into the next case's statements.

Answer : It is executed when the switch expression matches none of the case labels – like the else of an if statement.

Answer : When several case values need the same code, e.g. case 4: case 6: case 9: case 11: $days = 30; break;

Answer : match is an expression that returns a value, compares with strict ===, allows several comma-separated conditions per arm, needs no break, and throws UnhandledMatchError when nothing matches and there is no default.

Answer : PHP 8.0.

Answer : Replacing the opening brace with a colon and the closing brace with endif;, endswitch;, endfor;, endforeach; or endwhile; – useful when mixing PHP with HTML.

Answer : Yes. switch ($day) { case "Sat": case "Sun": echo "Weekend"; break; default: echo "Weekday"; } works with strings as well as numbers.

Answer : if ($marks >= 40) { echo "Pass"; } else { echo "Fail"; } – or with the ternary operator: echo $marks >= 40 ? "Pass" : "Fail";
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.

Q1. Which statement selects one of many blocks by comparing one value with several labels?

Show Answer

Correct Answer : B. switch
switch compares one expression with many case labels.

Q2. What happens if break is omitted at the end of a case?

Show Answer

Correct Answer : C. Execution falls through to the next case
Without break, the following case's statements also run.

Q3. Which keyword introduces an extra condition after if?

Show Answer

Correct Answer : B. elseif
PHP uses elseif (else if also works).

Q4. The PHP 8 match expression compares values using:

Show Answer

Correct Answer : B. ===
match uses strict identity comparison.

Q5. Which closes an if block written in alternative syntax?

Show Answer

Correct Answer : C. endif;
Alternative syntax uses endif;.

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.

  1. The PHP Group. (n.d.). PHP Manual – if. https://www.php.net/manual/en/control-structures.if.php
  2. The PHP Group. (n.d.). PHP Manual – switch. https://www.php.net/manual/en/control-structures.switch.php
  3. The PHP Group. (n.d.). PHP Manual – match. https://www.php.net/manual/en/control-structures.match.php
  4. The PHP Group. (n.d.). PHP Manual – Alternative syntax for control structures. https://www.php.net/manual/en/control-structures.alternative-syntax.php