0
0
PHPprogramming~20 mins

Default parameter values in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Default Parameter Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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();
?>
AHello, Guest!
BHello, !
CHello, name!
DError: Missing argument
Attempts:
2 left
💡 Hint
Check what happens when you call the function without any argument.
Predict Output
intermediate
2: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);
?>
A15
BError: Missing argument
C5
D10
Attempts:
2 left
💡 Hint
Look at the default value of the second parameter.
Predict Output
advanced
2: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);
?>
A8
B24
CError: Default value must be a constant expression
D12
Attempts:
2 left
💡 Hint
Default parameters can be expressions evaluated at compile time.
Predict Output
advanced
2: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();
?>
AWelcome, null!
BWelcome, !
CTypeError: Argument 1 passed must be of the type string, null given
DWelcome, Guest!
Attempts:
2 left
💡 Hint
Type hints apply to default values; null does not match string.
Predict Output
expert
3: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);
?>
A
Array ( [0] =&gt; item )
Array ( [0] =&gt; item )
B
Array ( [0] =&gt; item [1] =&gt; item )
Array ( [0] =&gt; item [1] =&gt; item )
C
Array ( [0] =&gt; item )
Array ( [0] =&gt; item [1] =&gt; item )
DError: Default value for parameters with reference must be null
Attempts:
2 left
💡 Hint
Check if default values can be references in PHP.