Bird
0
0

Identify the error in the following PHP code and select the correct fix:

medium📝 Debug Q14 of 15
PHP - Functions
Identify the error in the following PHP code and select the correct fix:
$count = 0;
function increment() {
    $count++;
}
increment();
echo $count;
ADeclare <code>$count</code> as static inside the function.
BAdd <code>global $count;</code> inside the function.
CPass <code>$count</code> as a parameter to the function.
DNo error; code works fine.
Step-by-Step Solution
Solution:
  1. Step 1: Understand variable scope in the function

    The function tries to increment $count, but without global, it treats $count as undefined local variable.
  2. Step 2: Fix the scope issue

    Adding global $count; inside the function tells PHP to use the global $count variable, allowing increment to work.
  3. Final Answer:

    Add global $count; inside the function. -> Option B
  4. Quick Check:

    Use global keyword to modify global variables inside functions [OK]
Quick Trick: Use 'global' to modify global variables inside functions [OK]
Common Mistakes:
  • Forgetting to declare global variables inside functions
  • Assuming variables are automatically global
  • Using static instead of global for global variables

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes