Complete the code to declare a global variable in PHP.
<?php $counter = 0; function increment() { global [1]; $counter++; } ?>
In PHP, to access a global variable inside a function, you must declare it with the global keyword followed by the variable name.
Complete the code to modify a global variable inside a function.
<?php $score = 10; function addPoints() { global [1]; $score += 5; } ?>
You must declare the global variable inside the function to modify it. Here, $score is the global variable.
Fix the error in the code to correctly access the global variable inside the function.
<?php $count = 5; function showCount() { echo [1]; } showCount(); ?>
To access a global variable inside a function without declaring it global, use the $GLOBALS array with the variable name as key.
Fill both blanks to create a function that modifies a global variable safely.
<?php $visits = 0; function visitPage() { [1] $visits; $visits [2] 1; } ?>
Declare the variable as global inside the function, then use the += operator to increase its value by 1.
Fill all three blanks to demonstrate why global state can cause bugs in PHP.
<?php
$flag = false;
function toggleFlag() {
[1] $flag;
if ($flag [2] false) {
$flag [3] true;
} else {
$flag = false;
}
}
?>Declare $flag as global to access it. Use == to check if it is false, then assign true to toggle it. This shows how global state can be changed unexpectedly.