0
0
PHPprogramming~20 mins

Variable scope in functions in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Scope Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of variable inside and outside function

What is the output of this PHP code?

PHP
<?php
$a = 5;
function test() {
    $a = 10;
    echo $a;
}
test();
echo $a;
A105
B55
C1010
D510
Attempts:
2 left
💡 Hint

Remember that variables inside functions have their own scope unless declared global.

Predict Output
intermediate
2:00remaining
Using global keyword inside function

What will this PHP code output?

PHP
<?php
$x = 3;
function add() {
    global $x;
    $x += 2;
    echo $x;
}
add();
echo $x;
A55
B53
C35
D33
Attempts:
2 left
💡 Hint

The global keyword lets the function access the variable outside its scope.

🔧 Debug
advanced
2:00remaining
Why does this code cause an error?

Why does this PHP code cause an error?

PHP
<?php
function foo() {
    echo $y;
}
$y = 7;
foo();
ABecause $y is defined after the function call
BBecause $y is a reserved keyword in PHP
CBecause variables cannot be echoed inside functions
DBecause $y is not defined inside the function scope
Attempts:
2 left
💡 Hint

Think about where variables are visible inside and outside functions.

Predict Output
advanced
2:00remaining
Static variable behavior in function

What is the output of this PHP code?

PHP
<?php
function counter() {
    static $count = 0;
    $count++;
    echo $count . ' ';
}
counter();
counter();
counter();
A0 1 2
B1 2 3
C1 1 1
D3 3 3
Attempts:
2 left
💡 Hint

Static variables keep their value between function calls.

🧠 Conceptual
expert
3:00remaining
Effect of variable scope on recursion

Consider this recursive PHP function:

What will be printed?

ACalls: 4
BCalls: 1
CCalls: 3
DCalls: 0
Attempts:
2 left
💡 Hint

Count how many times the function runs including the base case.