Bird
0
0

What will be the output of this PHP code?

medium📝 Predict Output Q4 of 15
PHP - Functions
What will be the output of this PHP code?
function greet(?string $name) {
    return $name ?? 'Guest';
}
echo greet(null);
AError: Argument must be string
BGuest
Cnull
DEmpty string
Step-by-Step Solution
Solution:
  1. Step 1: Understand the nullable parameter and null coalescing operator

    The function accepts a string or null. If null is passed, $name ?? 'Guest' returns 'Guest'.
  2. Step 2: Analyze the function call with null

    Calling greet(null) triggers the null coalescing operator to return 'Guest'.
  3. Final Answer:

    Guest -> Option B
  4. Quick Check:

    Nullable param with ?? operator returns default [OK]
Quick Trick: Use ?? to provide default for null values [OK]
Common Mistakes:
  • Expecting null to print
  • Assuming error on null input
  • Confusing ?? with || operator

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes