PHP Variables

Variables

Variables in PHP used for the same reason like in any other programming scripting language, i.e., to store dataIf we want to store any type of data for later use or to do some operation on it then we need to store it inside a variable. We can say that variables are like containers storing a particular type of data.

A variable can store different types of values like it can store integer value, float value, a string, boolean value, etc.In other languages, the programmer needs to specify first, what kind of data the variable he is about to declare, will store, i.e., whether it is an integer value, a string, a float value, etc.. these are called Strongly Typed Languages. The opposite of these languages is a Loosely Typed Language, which are not that much strict and allows the programmer to avoid declaring the data type of the variable's value, they figure out it of their own.

Some example of Loosely Typed Languages are JavaScript, Perl, PHP, etc. So, just like JavaScript we don't need to classify the data type of the variable in PHP also, it uses the same '$' sign. We will have a look at it in the examples, then you will have a clear idea about it, let's first got through some rules to define a variable in PHP.


Rules to define PHP variables

Every language has some rules which a programmer has to follow in order to code in a well defined manner. Some rules regarding defining PHP Variables are:

  • PHP Variables must begin with dollar($) sign followed by the variable identifier. An identifier is any name given to the variable.
  • PHP variable's identifier can be of any length, a long one($result, $even_number, etc.) or a short one with only a single alphabet($a, $k, etc.)
  • PHP Variable name should consist of only alphanumeric characters or underscores i.e., 'a-z', 'A-Z', '0-9' and '_'.
  • To assign a value to a PHP variable the assignment operator(=) is used. Example: $a=10;.
  • The PHP variables' name/identifier should never start with a number or any special character. Only underscore, or alphabets can be used at the start , after the '$' sign.
  • PHP variables are case-sensitive, i.e., $result is a different from $RESULT.

Creating PHP Variables

Let's quickly go through an example of how to create a PHP variable. We have already discussed it earlier that you need to use the '$' sign to declare the variable in PHP and not need to specify the data type of the value you are going to store in the variable.

Note: Remember that we are using Pure PHP code right now without embedding it with HTML, so don't get confuse, we will embed in the upcoming tutorials.
Syntax
$identifier = value;

Example

<!DOCTYPE html> <html> <body> <?php $txt = "Hello world!"; $x = 5; $y = 50; echo $txt; echo "<br>"; echo $x; echo "<br>"; echo $y; ?> </body> </html>

Output

Hello world!
5
50

In the example above, we have three variables '$txt', $x and $y. '$txt' has string value but '$x' and '$y' has integer value. We have not specified any datatype for them but still there are no errors because of using '$' sign.

The 'echo()' function is used to print the values of the variables, notice that here also we don't need to specify any data type.

Note: Always write a string value within quotes. You can use either single quotes(' ') or double quotes(" "), look at '$txt' variable.
Note: You can't only declare a variable and left it in PHP, like other programming languages. Whenever you create a variable, it is necessary to assign a value to it. Example:

$marks;- Not allowed

$marks=85;- Allowed


PHP Variable: Sum of two variables

Let's go through another example of adding two PHP variables' values. Remember that you cannot add a string value with an integer. We will use two integer values stored in two different variables and by using a third variable we will add their values:

Example

<!DOCTYPE html> <html> <body> <?php $x=8; $y=6; $z=$x+$y; echo $z; ?> </body> </html>

Output

14

In the example above, as you can see the '$z' variable is used to add the values of '$x' and '$y' by using the '+' addition operator.

Note: You can directly print the sum of the values without using the third variable '$z' by a slight change in the echo() function: echo($x+$y);

Scope of PHP Variables

The scope of PHP variable can be defined as to which extent we can use it inside the program. Whether we can only use the variable inside a single function or we can use it with multiple functions? So the scope of the variable will be the portion of code which is allowed to use that PHP variable's value, if your code cannot use a Variable's value then it is out of scope. It is an easy concept, we will look at different types of scopes with proper examples which will clear out things for you.

PHP has three different variable scopes:

  • Global
  • Local
  • Static

PHP Global Variables

PHP Global Variables

PHP variables which are not declared inside any function and can be used by any function are called Global variables. The advantage of using these variables is that any function can use it's value to do any kind of operation. It helps in saving time and memory by not creating variables again and again for a same value. But to use these variables inside a function we have to use $GLOBALS['variable name'].

Note: We will learn more about PHP functions in the upcoming tutorials, till now just see it as a block of statements.

Let's see an example:

Example

<!DOCTYPE html> <html> <body> <?php $x = 5; /* global scope */ function myTest() { /* using x inside this function will generate an error */ echo "<p>Variable x inside function is: $x</p>"; } myTest(); echo "<p>Variable x outside function is: $x</p>"; ?> </body> </html>

Output

Variable x inside function is:
Variable x outside function is: 5

In the example above, when we tried to access the global variable '$x' inside the 'myTest()' function, it showed an error stating 'undefined variable: x', because it is a global variable and we cannot use it directly within any function, we have to use the '$GLOBALS[]' array. Whereas when we tried to use '$x' outside of any function then we can access it normally without '$GLOBALS[]' array.


PHP Global Variable with $GLOBALS[]

$GLOBALS[] array stores all the global variables created in a program. The index of this array holds the name of the Global variable. So whenever any function needs to access a global variable it can use this array.

Let's see an exmaple:

Example

<!DOCTYPE html> <html> <body> <?php $x = 5; $y = 10; function myTest() { $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y']; } myTest(); echo $y; ?> </body> </html>

Output

15

In the example above, we access the global variables '$x' and '$y' inside the 'myTest()' function by using the '$GLOBALS[]' arrray and then added both values to '$y'. Although, we have not printed the value inside the function but you can do it by using echo($GLOBALS['y']);. Try it.


PHP Local Variable

The variables which are declared inside a function and can only be used within that particular function and not outside of it, are called Local Variables. If we declare any other variable with the same name outside the function as a variable inside the function then it will work as a whole different variable.

Let's see an example to clear out things:

Example

<!DOCTYPE html> <html> <body> <?php function myTest() { $x = 5; /* local scope */ echo "<p>Variable x inside function is: $x</p>"; } myTest(); /* using x outside the function will generate an error */ echo "<p>Variable x outside function is: $x</p>"; ?> </body> </html>

Output

Variable x inside function is: 5
Variable x outside function is:

In the example above, we have tried to access '$x', which is a local variable to 'myTest()' function, outside the function. It will show an error undefined variable: x because we cannot use '$x' outside the function unless there is another variable named '$x' exist outside the 'myTest()' function.

Note: You can use local variables with same name inside different functions, as one function is unaware of variables of another funtions.

PHP Static Variable

PHP always deletes the variables of a function from the memory after the successful execution of the fucntion. But what if we need any variable's value even after the execution of a function, like we may need to increment or decrement the value multiple times. So, what we can do to stop PHP from deleting variable from the memory?, we use the static variables.

Static variables in PHP are declared using the keyword 'static'. After declaring any PHP variable 'static', it will not get deleted from the memory till the program is getting executed.

Let's see an example of static keywords:

Example

<!DOCTYPE html> <html> <body> <?php function myTest() { static $x = 0; echo $x; $x++; } myTest(); echo " "; myTest(); echo " "; myTest(); ?> </body> </html>

Output

0   1   2

In the example above, we have declared '$x' as static. It haven't got destroyed after each fucntion call so it gets incremented by '1' each time it is called and we got an incremented value. So, you can say that in each function call the variable retains the value of it's previous function calls. But if we won't use the static keyword with '$x' then you will get the output as 0 0 0 because after each execution of the function, the variable gets destroyed and it is initialized again the value '0'.


PHP $ vs $$

We have till now used the '$' sign to create variables in PHP but there is another '$$' sign which it used. So, what's the difference between these two? Let's see:

We are familiar with the working of '$', it creates the variable in PHP and stores a value in it but the '$$' is known as a reference variable. The '$$' variable is used to refer to the value of the '$' variable. It means that when we use the '$$' variable, we are indirectly referrring to a variable named as value stored in the '$' variable.

Let's see an example to clear out things:

Example

<!DOCTYPE html> <html> <body> <?php // Variable declaration and initialization $var = "Hello"; $Hello = "Coderepublics"; // Display the value of $var and $$var echo "$var
"; echo $$var; echo "\n\n"; ?> </body> </html>

Output

Hello
Coderepublics

In the example above, we have two variables '$var' and '$Hello'. As you can see '$Hello' is named same as the value of '$var'. When we printed '$var' then the value "Hello" gets printed which is normal, but when we printed '$$var', then the PHP interpreter looked for the value of '$var', which is 'Hello' and then looked for a variable named as '$Hello' and printed its value.

Create some programs by yourself and then you will get a clear idea of how to use these variables if things are still not clear to you.

It was all about PHP variables and we hope that we have made it easy for you to understand it easily. Stay with us to get more PHP tutorials, click on next.



Color Picker

List of color names supported by all browser »



Character Code

List of character codes to display special character »



Language Code

List of all language supported by all browser »



Country Code

List of Country code supported by all browser »

Latest Updates

PHP Introduction

How to Run a PHP program in Xampp?

How can I create a phpinfo.php page?

How to Define a Variable in PHP

PHP Echo and Print Statements

Working with PHP Operators

Understanding the PHP Data Types

How to Write Comments in PHP

How to Define a Constant in PHP

PHP if...else...elseif Statements