0
0
PHPprogramming~10 mins

Match expression (PHP 8) - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to return the correct day name using match expression.

PHP
<?php
$dayNumber = 3;
$dayName = match($dayNumber) {
    1 => 'Monday',
    2 => 'Tuesday',
    [1] => 'Wednesday',
    4 => 'Thursday',
    5 => 'Friday',
    6 => 'Saturday',
    7 => 'Sunday',
    default => 'Invalid day'
};
echo $dayName;
Drag options to blanks, or click blank then click option'
A0
B3
C5
D8
Attempts:
3 left
💡 Hint
Common Mistakes
Using a number that does not match Wednesday, like 5 or 0.
Forgetting to use the exact number for the case.
2fill in blank
medium

Complete the code to return the correct message for a given status code using match expression.

PHP
<?php
$statusCode = 404;
$message = match($statusCode) {
    200 => 'OK',
    400 => 'Bad Request',
    [1] => 'Not Found',
    500 => 'Server Error',
    default => 'Unknown Status'
};
echo $message;
Drag options to blanks, or click blank then click option'
A404
B200
C300
D500
Attempts:
3 left
💡 Hint
Common Mistakes
Using 300 or 200 which do not correspond to 'Not Found'.
Confusing 500 with 404.
3fill in blank
hard

Fix the error in the match expression to correctly handle fruit colors.

PHP
<?php
$fruit = 'apple';
$color = match($fruit) {
    'banana' => 'yellow',
    'apple' => [1],
    'grape' => 'purple',
    default => 'unknown'
};
echo $color;
Drag options to blanks, or click blank then click option'
A'red'
Bred
C"red"
D'green'
Attempts:
3 left
💡 Hint
Common Mistakes
Using unquoted strings like red which cause errors.
Using double quotes which is valid but not the intended answer here.
4fill in blank
hard

Fill both blanks to create a match expression that returns the season for a given month number.

PHP
<?php
$month = 11;
$season = match(true) {
    $month >= 3 && $month <= 5 => [1],
    $month >= 6 && $month <= 8 => [2],
    $month >= 9 && $month <= 11 => 'Autumn',
    default => 'Winter'
};
echo $season;
Drag options to blanks, or click blank then click option'
A'Spring'
B'Summer'
C'Winter'
D'Autumn'
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up the seasons for the month ranges.
Forgetting to quote the season names.
5fill in blank
hard

Fill all three blanks to create a match expression that returns the type of a variable.

PHP
<?php
$var = 3.14;
$type = match(gettype($var)) {
    [1] => 'integer',
    [2] => 'string',
    [3] => 'float',
    default => 'other'
};
echo $type;
Drag options to blanks, or click blank then click option'
A'integer'
B'string'
C'double'
D'float'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'float' instead of 'double' for the float type.
Not quoting the type strings.