0
0
PHPprogramming~10 mins

Global keyword behavior 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 access the global variable inside the function.

PHP
<?php
$number = 10;
function showNumber() {
    global [1];
    echo $number;
}
showNumber();
?>
Drag options to blanks, or click blank then click option'
Anumber
B$number
C$GLOBALS
Dglobal
Attempts:
3 left
💡 Hint
Common Mistakes
Including the $ sign after the global keyword.
Using $GLOBALS array instead of the global keyword here.
2fill in blank
medium

Complete the code to modify the global variable inside the function.

PHP
<?php
$count = 5;
function increment() {
    global [1];
    $count++;
}
increment();
echo $count;
?>
Drag options to blanks, or click blank then click option'
A$count
Bglobal
Ccount
D$GLOBALS
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to modify the variable without declaring it global.
Using $count instead of count after global keyword.
3fill in blank
hard

Fix the error in the code to correctly access the global variable inside the function.

PHP
<?php
$value = 20;
function display() {
    echo [1];
}
display();
?>
Drag options to blanks, or click blank then click option'
A$value
Bglobal value
Cvalue
D$GLOBALS['value']
Attempts:
3 left
💡 Hint
Common Mistakes
Using the variable name without $ or global keyword.
Trying to echo the variable directly without global or $GLOBALS.
4fill in blank
hard

Fill both blanks to create a function that modifies a global variable using the $GLOBALS array.

PHP
<?php
$score = 0;
function addPoint() {
    [1]['score'][2];
}
addPoint();
echo $score;
?>
Drag options to blanks, or click blank then click option'
A$GLOBALS
B$score
C++
D--
Attempts:
3 left
💡 Hint
Common Mistakes
Using $score directly inside the function without global or $GLOBALS.
Using the decrement operator instead of increment.
5fill in blank
hard

Fill all three blanks to create a function that resets a global variable to zero using the global keyword.

PHP
<?php
$counter = 10;
function resetCounter() {
    global [1];
    [2] = [3];
}
resetCounter();
echo $counter;
?>
Drag options to blanks, or click blank then click option'
Acounter
B$counter
C0
Dnull
Attempts:
3 left
💡 Hint
Common Mistakes
Using $counter after the global keyword.
Assigning null instead of zero.