Programming Languages PHP Subjective
Sep 23, 2025

What will be the output of this PHP 8+ code? Explain the behavior of match expression with type juggling.

Detailed Explanation

Code Analysis:

$value = "2";
$result = match($value) {
    1 => "one",
    2 => "two", 
    "2" => "string two",
    default => "unknown"
};
echo $result;

Output: "two"

Explanation:

  • Match expressions use strict comparison (===) by default
  • Since $value is string "2", it matches the first case where 2 (integer) is compared
  • However, match does type coercion for the first matching case
  • The string "2" matches integer 2, so "two" is returned
  • If we had strict types enabled, this would behave differently

Key Difference from Switch: Match is exhaustive and uses strict comparison, but still allows type coercion in pattern matching.

Discussion (0)

No comments yet. Be the first to share your thoughts!

Share Your Thoughts
Feedback