Challenge - 5 Problems
Default Parameter Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of function with default parameter
What is the output of this PHP code?
PHP
<?php function greet($name = "Guest") { return "Hello, $name!"; } echo greet(); ?>
Attempts:
2 left
💡 Hint
Check what happens when you call the function without any argument.
✗ Incorrect
The function greet has a default value 'Guest' for the parameter $name. When called without argument, it uses this default.
❓ Predict Output
intermediate2:00remaining
Default parameter with multiple arguments
What is the output of this PHP code?
PHP
<?php function add($a, $b = 10) { return $a + $b; } echo add(5); ?>
Attempts:
2 left
💡 Hint
Look at the default value of the second parameter.
✗ Incorrect
The function add has $b default to 10. Calling add(5) means $a=5 and $b=10, so sum is 15.
❓ Predict Output
advanced2:00remaining
Default parameter with expression
What is the output of this PHP code?
PHP
<?php function multiply($x, $y = 2 * 3) { return $x * $y; } echo multiply(4); ?>
Attempts:
2 left
💡 Hint
Default parameters can be expressions evaluated at compile time.
✗ Incorrect
The default value for $y is 2 * 3 = 6. multiply(4) returns 4 * 6 = 24.
❓ Predict Output
advanced2:00remaining
Default parameter with null and type hint
What is the output of this PHP code?
PHP
<?php function welcome(string $name = null) { if ($name === null) { return "Welcome, Guest!"; } return "Welcome, $name!"; } echo welcome(); ?>
Attempts:
2 left
💡 Hint
Type hints apply to default values; null does not match string.
✗ Incorrect
PHP type hints require arguments, including defaults, to match the declared type. Null does not match string, causing a TypeError when the function is called without an argument.
❓ Predict Output
expert3:00remaining
Default parameter with mutable object
What is the output of this PHP code?
PHP
<?php function addItem(array &$arr = []) { $arr[] = "item"; return $arr; } $a = addItem(); $b = addItem(); print_r($a); print_r($b); ?>
Attempts:
2 left
💡 Hint
Check if default values can be references in PHP.
✗ Incorrect
In PHP, default values for parameters passed by reference must be null. Using [] as default for a reference parameter causes a fatal error.