If Statement Variable Scope In PHP

PHP Logo Variable scope is the context within your code in which a variable is defined and able to accessed. If you try to access a variable that is out of scope, the variable will be undefined and you will not get the results you are expecting.

In PHP, variables all exist within the same scope when your code is inline or included in an include or require statement. Classes and functions have their own scope. If statements do not have their own variable scope.

To better understand what all this means, here are a couple examples.

In this example we simply define a variable then access the contents of that variable. You get the expected result of being able to retrieve the expected value.

Here, however, we are going to try to access the value of a variable defined outside of the scope of the echo statement. The result is that the variable being accessed is actually undefined.

The scope problem goes both ways. Here we’ll define a variable within a function then try to retrieve its value outside of the function. Again the variable is undefined.

If statements do NOT have their own variable scope. This is a common “gotcha” in PHP because it is easy to assume that all code blocks set up their own variable scope. This is not the case with if/else statements.

Since if/else statements do not create their own variable scope, this code will print the expected messages. Both $morning_message and $evening_message are defined in the if/else blocks even though they were declared outside the if/else block.

Likewise, you can access variables defined within an if/else block from outside of the block.

4 thoughts on “If Statement Variable Scope In PHP

  1. JP says:

    i have a code where i declared a variable inside an if statement and i have another if statement wherein i need to access the said variable i declared inside the first if statement.. problem is, i can’t get the result i need to when i try to print it to the second if statement.. how should i do it? thanks in advance! GOD bless! ^^

    • Lee says:

      It’s hard to know what to say without seeing your code but you could try declaring the variable outside of the “if” statements.

  2. codywohlers says:

    I think this is the same for select-case, for and while loops as well right?

  3. Yasir says:

    Same problem with my code as well, as is said by “JP”.

Leave a Reply

Your email address will not be published. Required fields are marked *