0
0
PHPprogramming~20 mins

Global keyword behavior in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Global Scope Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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;
?>
AError: Undefined variable
B15
C10
D5
Attempts:
2 left
💡 Hint
Remember that the global keyword allows access to the variable outside the function.
Predict Output
intermediate
2: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;
A7 7
B12 7
CError: Undefined variable $x
D5 7
Attempts:
2 left
💡 Hint
Inside the function, $x is not declared global and is used before assignment.
🔧 Debug
advanced
2: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;
ABecause $count is not declared global inside the function, so local $count is incremented but global remains 0.
BBecause $count is a constant and cannot be changed.
CBecause increment() is never called.
DBecause PHP does not allow modifying global variables inside functions.
Attempts:
2 left
💡 Hint
Check if the function has access to the global variable.
📝 Syntax
advanced
2:00remaining
Identify the syntax error related to global keyword
Which option contains a syntax error in using the global keyword?
Afunction foo() { global $var; $var = 10; }
Bfunction foo() { global $var; echo $var; }
Cfunction foo() { global var; var = 10; }
Dfunction foo() { global $var; $var += 5; }
Attempts:
2 left
💡 Hint
Check if the variable name after global has the correct syntax.
🚀 Application
expert
2: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();
A4
B3
C1
D0
Attempts:
2 left
💡 Hint
The function adds a new element and then removes duplicates.