What is the output of this PHP code?
<?php $a = 5; function test() { $a = 10; echo $a; } test(); echo $a;
Remember that variables inside functions have their own scope unless declared global.
The function test() has its own local variable $a set to 10, which it prints. Outside the function, $a is 5, so the output is 10 then 5, combined as 105.
What will this PHP code output?
<?php $x = 3; function add() { global $x; $x += 2; echo $x; } add(); echo $x;
The global keyword lets the function access the variable outside its scope.
The function modifies the global $x by adding 2, so inside the function it prints 5. After the function call, $x remains 5, so the final output is 55.
Why does this PHP code cause an error?
<?php function foo() { echo $y; } $y = 7; foo();
Think about where variables are visible inside and outside functions.
The variable $y is defined outside the function and is not global inside foo(). Without global $y; inside the function, $y is undefined there, causing an error.
What is the output of this PHP code?
<?php function counter() { static $count = 0; $count++; echo $count . ' '; } counter(); counter(); counter();
Static variables keep their value between function calls.
The static variable $count starts at 0 and increments each time counter() is called. The outputs are 1, then 2, then 3, printed with spaces.
Consider this recursive PHP function:
What will be printed?
Count how many times the function runs including the base case.
The function is called three times: for n=3 (calls=1), n=2 (calls=2), and n=1 (calls=3, base case). It prints "Calls: 3" at the base case.