How can the scope of variables in PHP affect the behavior of code blocks within a script?

The scope of variables in PHP refers to where in the script a variable is accessible. If a variable is defined within a specific code block (such as a function), it may not be accessible outside of that block. This can affect the behavior of the code if variables are not properly scoped, leading to errors or unexpected results. To ensure variables are accessible where needed, it is important to understand and correctly define their scope within the script.

$globalVariable = "I am a global variable";

function testFunction() {
    $localVariable = "I am a local variable";
    echo $localVariable;
}

testFunction(); // Output: I am a local variable
echo $globalVariable; // Output: I am a global variable