PHP Variables


August 23, 2021, Learn eTutorial
3418

In this PHP tutorial, you will learn all about variables, the basic unit of programming language. We will discuss in detail what is a variable in PHP, how to name, declare and initialize a variable with the help of examples.

What is meant by variables?

PHP - Variables

A variable is a set of memory spaces in a computer that may be used to store data and to specify a unique name for that. A unique address is assigned to each byte of data in RAM.

How to name variables in PHP?

  • In PHP we use the “$” symbol before the variable name to represent a variable. 
    $name  
    
  • A variable in PHP will only contain the alphanumeric (a-z, A-Z, 0-9) character and the underscore (_). 
    $name                  // Valid Variable Name
    $Age                   // Valid Variable Name
    $Check_Name            // Valid Variable Nam 
    
  • Every variable must start with an alphabet (a-z, A-Z) or an underscore (_). On the other hand numeric (0-9) or special characters cannot be 
    $name   // Valid Variable Name
    $_age   // Valid Variable Name
    $01Name // Invalid Variable Name
    $#Name  // Invalid Variable Name 
    
  • Like other languages, the variable name must not contain white space.
    $check name // Invalid Variable Name 
    
  • The variables in PHP are case-sensitive we can give variable names both $name and $Name are two different variables. we can see it in an example
    $name = "John";
    $NAME = "Doe";
    echo "First Name: $name Last Name: $NAME";
     
    
    
    First Name: John Last Name: Doe
    

How to declare a variable in PHP?

  • In PHP it is not required to declare a variable before using it in the program. It automatically assigns the data type according to the value of the variable.
  • When a variable is declared it can be reused in the entire program
  • The assignment operator (=) is used to assign the values into the variable

Assigning value into the variables in PHP

PHP - Variables

We use the “=” symbol to assign value to the variable.

Syntax


$variable_name = value;
 

Example


$name = "John";
echo $name;

 

Output:


John

There are 8 data types which we use to construct variables in PHP:

Array

Boolean

Double or Float

Integer

NULL

Object

Resources

String


$count   = 1;              // Variable hold an integer value;
$count   = “one”;     // Variable hold a String value;
$num      =  1.5;         // Variable hold a Float value;
$num      =  True;       // Variable hold a Boolean value;
 

We use the built-in function var_dump() to print the data type of the entered variable.

Syntax


var_dump(var1, var2, ...);
 

Checking the datatype of the variables


$name = "John";
$age = 25;
$salary = 1201.78;
var_dump($name);
var_dump($age);
var_dump($salary);
 

Output:


string(4) "John"
int(25)
float(1201.78)

What is Variable Scope in PHP?

In PHP we can declare a variable anywhere in the program. The scope of a variable refers to the range of the program in which it may be accessed. In other words, A variable's scope is the block of the program where it is defined and may be accessed. There are three types of variable scope they are:

PHP - Variables
  1. Static Scope
  2. Local Scope
  3. Global Scope

1)    Static Scope

One of the features of PHP is that it deletes the variable that has completed its execution and the memory will be freed for further processes. Even after the function has been completed, we may need to store some of the variables for further use. As a result, a static variable is a key component of variable scoping. To define a variable to be static by just simply putting the keyword STATIC in front of its name, such variables are referred to as the static variables. Only a local function has static variables. When a function is finished/executed, all of its variables are normally erased. However, there are some occasional needs when we do not want a local variable to be destroyed. We may need it for another execution. For those purposes, we may have to first declare the variable as the static variable to accomplish this. Then, when the function is called again, that variable will still hold the information it had the last time it was invoked. A static variable will not lose its value when the function finishes, unlike variables specified as function parameters, which are deleted when the function exits. It will also retain its value if the function is called again. It's worth noting that the variable is still a local variable. 

Example for a static scope:


function counting()
{
    static $x = 1;
    echo "Count $x \n";
    $x++;
}
counting();
counting();
counting();
 

Output:


Count 1 
Count 2 
Count 3

In the above example, we can see that the value of the variable x is defined at the first as the static variable, and the value is only assigned at once and every time the function is called the value doesn't affect the program.

2)    Local Scope

The variables declared within a function are referred to as the function's local variables. The local variables can only be referenced within that function. The scope of these local variables is limited to the function in which they are declared. Because these variables have local scope, they can't be accessed outside of the function. A variable declared outside of the function with the same name is not the same as a variable declared within the function. Any assignment made outside of that function is treated as a completely separate variable from that one in the function.

Example of local variable


function check()
{
    $x = "learnetutorials.com";
    echo "You are at $x";
}
check();
echo $x;

 

Output:


You are at learnetutorials.com

In the above example, we can see that the variable ‘x’ is declared in the block of the function and when it is used in the function it perfectly works and then tries to use it outside the function it won’t work because the variable ‘x’ is a local variable.

3)    Global Scope

The variables stated outside the function are known as global variables. The global variables are accessible throughout the program. We have to use the GLOBAL keyword before the variable to access the global variable within a function. The global variables can be directly accessed or utilized outside of the function without the usage of any keyword. As a result, no keyword is required to access a global variable outside of the function. A global variable, unlike local variables, can be accessed from anywhere in the program. A global variable must be expressly defined as global in the function in which it is to be modified before it can be modified. For such a purpose, we use the $GLOBALS array as another approach to using the global variable inside the function. By putting the keyword GLOBAL in front of the variable that needs to be recognized as global. When you apply this keyword in front of an existing variable, PHP will use the variable with that name. If you try to access a global variable inside the function without using the global keyword, you'll get an error saying the variable is undefined.

Example of the global variable


$name = "Jhon Doe";
function welcome()
{
    echo "Hello! $name welcome to learnetutorials.com \n";
}
welcome();
echo "$name how are you doing?";
 

Output:


Hello!  welcome to learnetutorials.com 
Jhon Doe how are you doing?

In the above example we can see that when using the variable declared outside the function is used in the function it won’t work and it will be considered as an error.

 Example of using keyword global


$name = "Jhon Doe";

function welcome()
{
    global $name;
    echo "Hello! $name welcome to learnetutorials.com \n";
}
welcome();

 

Output:


Hello! Jhon Doe welcome to learnetutorials.com 
Jhon Doe how are you doing?

In the above example, we can see that when the global keyword is used in front of the variable defined outside the function it’s accepted in the function block as well.

Example for Variable Scope in PHP

PHP - Variables

In the above example, we can see that the variable ‘x’ is defined outside the functions and we have learned that every variable defined outside the functions is the Global variable. And the variable ‘y’ is defined as a static variable we can see that the keyword static set the variable as a static variable. The variable ‘z’ and ‘k’ are defined in the function block and every variable defined inside the function block will be a local variable that can only be used inside the current function only, and we can also see that the variable ‘x’ is used inside the function as a global variable by using the keyword global in front of it and if we change the value of the variable ‘x’ inside that function then the value will also change in the entire program.