0
0
PHPprogramming~5 mins

Match expression (PHP 8) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a match expression in PHP 8?
A match expression is a new control structure in PHP 8 that allows you to compare a value against multiple conditions and return a result. It is similar to switch but more concise and returns a value.
Click to reveal answer
intermediate
How does match differ from switch in PHP?
Unlike switch, match is an expression that returns a value, supports strict type comparisons, does not allow fall-through, and requires all cases to be handled or a default to be provided.
Click to reveal answer
intermediate
What happens if no case matches and no default is provided in a match expression?
If no case matches and there is no default case, a UnhandledMatchError exception is thrown at runtime.
Click to reveal answer
beginner
Can a match expression have multiple conditions for a single case?
Yes, you can list multiple conditions separated by commas for a single case in a match expression, and if any condition matches, that case's value is returned.
Click to reveal answer
beginner
Write a simple match expression that returns 'Weekend' for 6 or 7, and 'Weekday' for 1 to 5.
Example:<br>
$dayType = match($day) {<br>  6, 7 => 'Weekend',<br>  1, 2, 3, 4, 5 => 'Weekday',<br>  default => 'Invalid day',<br>};
Click to reveal answer
What type of comparison does match use in PHP 8?
ALoose comparison (==)
BStrict comparison (===)
CBitwise comparison
DReference comparison
What happens if a match expression has no matching case and no default?
AReturns false
BReturns null
CExecutes the last case
DThrows an UnhandledMatchError exception
Which of these is NOT true about match expressions?
AThey can return a value
BThey require all cases to be handled or a default
CThey allow fall-through between cases
DThey use strict type comparison
How do you specify multiple conditions for one case in a match expression?
ASeparate conditions with commas
BUse multiple <code>case</code> lines
CUse logical OR operators
DUse arrays
Which PHP version introduced the match expression?
APHP 8.0
BPHP 7.3
CPHP 8.1
DPHP 7.4
Explain how a match expression works in PHP 8 and how it differs from a switch statement.
Think about how match is more like a value-returning expression than a statement.
You got /5 concepts.
    Write a match expression that categorizes a number as 'small' for 1-3, 'medium' for 4-6, and 'large' for 7-9, with a default of 'unknown'.
    Use commas to list multiple values for each case.
    You got /3 concepts.