Challenge - 5 Problems
Global Scope Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of modifying a global variable inside a function
What is the output of this PHP code?
PHP
<?php $a = 5; function test() { global $a; $a = $a + 10; } test(); echo $a; ?>
Attempts:
2 left
💡 Hint
Remember that the global keyword allows access to the variable outside the function.
✗ Incorrect
The global keyword inside the function links $a to the global $a. So modifying $a inside the function changes the global variable. After calling test(), $a becomes 15.
❓ Predict Output
intermediate2:00remaining
Effect of missing global keyword on variable inside function
What will this PHP code output?
PHP
<?php $x = 7; function addFive() { $x = $x + 5; echo $x; } addFive(); echo $x;
Attempts:
2 left
💡 Hint
Inside the function, $x is not declared global and is used before assignment.
✗ Incorrect
Without the global keyword, $x inside addFive() is local. The right side $x is undefined (null, treated as 0), so $x = 5, echoes 5 (with notice). Global $x remains 7, outputs "57".
🔧 Debug
advanced2:00remaining
Why does this code not update the global variable?
This PHP code tries to update a global variable inside a function but fails. Why?
PHP
<?php $count = 0; function increment() { $count++; } increment(); echo $count;
Attempts:
2 left
💡 Hint
Check if the function has access to the global variable.
✗ Incorrect
Without the global keyword, $count inside the function is local and uninitialized, so incrementing it does not affect the global $count.
📝 Syntax
advanced2:00remaining
Identify the syntax error related to global keyword
Which option contains a syntax error in using the global keyword?
Attempts:
2 left
💡 Hint
Check if the variable name after global has the correct syntax.
✗ Incorrect
In PHP, the global keyword must be followed by a variable name with a $ sign. Option C misses the $ sign, causing a syntax error.
🚀 Application
expert2:00remaining
How many items are in the global array after function call?
Consider this PHP code. How many elements does the global array $data have after calling updateData()?
PHP
<?php $data = [1, 2, 3]; function updateData() { global $data; $data[] = 4; $data = array_unique($data); } updateData();
Attempts:
2 left
💡 Hint
The function adds a new element and then removes duplicates.
✗ Incorrect
The function adds 4 to the global array $data, then removes duplicates. Since 4 is new, the array has 4 elements after the call.