0
0
PHPprogramming~10 mins

Null coalescing operator in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to assign $value to $result if $value is set, otherwise assign 'default'.

PHP
$result = $value [1] 'default';
Drag options to blanks, or click blank then click option'
A||
B??
C&&
D?:
Attempts:
3 left
💡 Hint
Common Mistakes
Using '||' instead of '??' which checks for truthiness, not null.
Using '?:' which is the ternary shorthand but behaves differently.
2fill in blank
medium

Complete the code to get the value of $_GET['name'] or use 'Guest' if it is not set.

PHP
$name = $_GET['name'] [1] 'Guest';
Drag options to blanks, or click blank then click option'
A??
B&&
C?:
D||
Attempts:
3 left
💡 Hint
Common Mistakes
Using '||' which checks for truthiness and can cause unexpected results.
Using '?:' which requires the left operand to be evaluated differently.
3fill in blank
hard

Fix the error in the code to safely assign $username from $_POST['user'] or 'anonymous' if not set.

PHP
$username = $_POST['user'] [1] 'anonymous';
Drag options to blanks, or click blank then click option'
A||
B&&
C?:
D??
Attempts:
3 left
💡 Hint
Common Mistakes
Using '||' which can cause warnings if the key does not exist.
Using '?:' which requires the left operand to be set and truthy.
4fill in blank
hard

Fill both blanks to create an array $settings with keys 'theme' and 'language' using null coalescing operator to provide defaults.

PHP
$settings = [
    'theme' => $userSettings['theme'] [1] 'light',
    'language' => $userSettings['language'] [2] 'en'
];
Drag options to blanks, or click blank then click option'
A??
B||
C?:
D&&
Attempts:
3 left
💡 Hint
Common Mistakes
Using '||' which checks truthiness and can cause unexpected results.
Using '?:' which behaves differently and may cause warnings.
5fill in blank
hard

Fill all three blanks to assign $finalName using nested null coalescing operators to check $input['first'], $input['nickname'], or default to 'User'.

PHP
$finalName = $input['first'] [1] $input['nickname'] [2] [3];
Drag options to blanks, or click blank then click option'
A??
C'User'
D||
Attempts:
3 left
💡 Hint
Common Mistakes
Using '||' which checks truthiness and can cause unexpected results.
Not nesting the operators correctly.