Learn PHP Variables in detail

The ultimate use of a variable is to store data and understand its concept is the foremost step to start working with PHP.

What is Variable?

A variable is a space of computer memory that has a name to be recognized and can contain some value for us such as text, number or etc. Its like when you meet somebody at a park and saying to him “What is your name?” and he replies with  a name or with weird look. In PHP we can say that name is the variable and weird look is its NULL value(Means he has nothing) but here in PHP there are certain rules while declaring the variable.

The variable name must begin with ‘$’ sign. Be careful it is necessary for variables name that doesn’t start with any of ‘+ – , . * & ^ % $ # @ ! ( ) = \ / ? ~ `’ characters and they shouldn’t have with number digits just after $ sign.

There is a kind of variable which has been defined with PHP and the contents of them have been set by PHP and we cannot change their values. They are called ‘Predefined Variables’. Their name starts with ‘$_’ or ‘__’. We can also have variables in this format but the name must have no conflict with PHP’s predefined variables.

Important points to remember before defining a variable in PHP :

  • A variable in PHP always starts with $ sign followed by the name of the variable. (Ex: $var). Here $ sign represents variable signature and “var” is a variable name in php.
  • A variable must starts with a letter but not with any special character or a number. Of course you can use an underscore (_) to define a variables in PHP.
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
  • PHP variables are case-sensitive. ($name and $NAME are treated two different variables).
  • You may not use spaces within the name of a variable. (Instead, the underscore is commonly used to separate words.)

There are two main variable naming conventions, determined by how you delineate words. These are the so-called camel-hump (named because of the way capital letters break up the word—for example, $FirstName) and underscore ($first_name) styles.

This rules are also applied for functions and user-defined objects which is known as identifier except the fact that functions do not start with $ Sign.

Here we have some examples of variables, furthermore we’ll discuss about their types as well:

$t= true;
$Num= 567.7863;
$_str= 'Hello';

As you see, the way that you can enter a value to the variable is to put the variable name in left, then using ‘=’ sign and after that, the value should come. You can also put a variable value into another one; And you can also sum, minus, or other mathematical operations on variables and putting the result to another variable. Some basic examples:

  $Num= 6*2+9*2;  // $Num= 21
  $x= $Num/3;  // $x= 10

If you don’t initialize the variable, it will have its default value. This value is dependent on the type of the variable and in general it is one of these values: ((false, 0 or empty string)).

An exciting capability of variables is ‘Variable Variables’, that is, one variable name can be set by another variable value. This kind of variables has two dollar sign ($$variable) at beginning. Look at the example first:

     $b= 'Book';

        $$b= 'Physics';  // is the same with $Book= 'Physics'

        echo $b;   // Prints "Book"

        echo $$b;  // Prints "Physics"

        echo $Book;  // Prints "Physics"

As you see the value of one variable (‘Book’) becomes the name of another one and the value of second variable is accessible in two ways ($$b or $Book).

Notice: it is not allowed to use dots between a variable name and it leads to parse error.

PHP Variable Types

We have different types of variables in php as other programming language.

The first one introduced here is ‘Boolean Variables’ which can hold only the value ‘True’ or ‘False.’ It is useful for saving whether or not a setting, an operation or etc is defined or done when it is needed. As it comes in the future, you can use them in conditional expressions. Here is another example

$con= true;

$Private= false;

Echo $con; echo $Private;

When you run the page the only thing that you see is ‘1’. Because the ‘true’ value equals to ‘1’ and ‘false’ value equals to nothing or in some cases to 0. Another usage of this variable is to save a function returned value. If the answer comes from a function is ‘true’ the ‘true’ value will be saved to your variable or if the reverse happens the ‘false’ value will be saved. You’ll learn about functions widely in the future.

For example if you have complex program and you are worried about that you have ever used one variable name or set an initial value of it or not, you can use ‘isset($variable)’ function. The output of this function is ‘true’ or ‘false’ (1 or 0):


echo (int) isset($a2); echo (int) isset($a1)

$a2 doesn’t have used before so the ‘isset()’ function returns ‘false’. The ‘(int) statement is for changing empty (false) value to the ‘integer’ number (0).

Another variable that we often see is ‘integer’ variable. It covers a wide range of true numbers (32 or 64 bit) without any point between them. It can hold negative, hexadecimal and octal numbers, too. Here are some examples:

$int1= 2045 // Positive number

$int2= -3567 // Negative number

$a = 0123; // octal number (equivalent to 83 decimal)
$b = 0x1A; // hexadecimal number (equivalent to 26 decimal)

There are some Pints about ‘integer’ numbers.

First: If you write a number greater than the range it becomes a float number as below (float numbers aren’t essentially true numbers.

$int1= 254642316454878745421544574

// the result is about 2.546423E+26 that is a sign for 2.546423 * 1026

Second: This point is about how we can change other variables types to ‘integer’. There are two ways. One by putting ‘(int)’ after the functions as what we said about ‘echo (int) …’; And another way is by using ‘intval( )’ function such as :

$tf= false;

Echo (int) $tf;  //echo 0

$tf2= intval($tf);

Echo $tf2  //echo 0

Third: Do not make ‘integer’ type with undefined fractions such as below:

Echo (int) ((0.1+0.7)*10);  // Prints 7

Echo ((0.1+0.7)*10);  // Prints 8

This will return 7 instead of 8, Because of small error in calculating by computer. Leave them be float numbers as default (remove ‘(int)’).

Another kind of variables is ‘float’ that can be expressed in these models:

$a= 12.6887;

$b= 1.2e5;  // (or capital E) equals to 120000 or 1.2 * 105

$c= 2.5E-3;  // equals to 0.0025 or 2.5 * 10-3

The error we mentioned in the previous lesson is due to some fractions which have no true equivalent, like ‘1/3’ and it is a float number like this ‘Description: 0.3.’ So be careful with last number (digit) of the results of your calculations.

And the other type of variable discussed here is string, which consists of different characters which exist in all computers (256 in fact). For ‘strings’ we have no numerical value, i.e. ‘a,’ ‘1’ and ‘2’ are the same as a form, and are known as a single string.

We have two important ways to define a ‘string’ variable: one is to set a value between two single quotes (‘) and the other is to do the same for double quotes (‘). You have to put a quotation mark after a ‘\’ backslash if you want a quotation between the ‘strings,’ or you can open the string with double quotes and put the quotes between them, with single quotes; and you can do it backwards. Now let’s start taking a few examples:

$a= 'Hello';

$b= "Hello";

$c= 'I say \'Hello\' to all';

$d= "I say 'Hello' to all";

$f= 'I go to "Harvard" university'

If you echo the above variables you will have ((Hello)) for first two examples and ((Hello, I say ‘Hello’ to all)) for the next two; and for the final one ((I go to “Harvard” university)) will appear.

If you have variable inside the string with one quote it doesn’t work, that means:

$a= 'Mike';

$b= 'Hello $a';

Echo $b;  // it will print ((Hello $a)) not ((Hello Mike))

But double quote effect is reversed:

$a= 'Mike';

$b= "Hello $a";

Echo $b;  // it will print ((Hello Mike)) not ((Hello $a))

Type Juggling

In PHP you don’t need to explicitly specify a type for variables. A variable’s type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable $var$var becomes a string. If you then assign an integer value to $var, it becomes an integer.

An example of PHP’s automatic type conversion is the addition operator ‘+’. If any of the operands is a float, then all operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated.

Example :

$myvar = "0"; // $myvar is string (ASCII 48)
$myvar += 2; // $myvar is now an integer (2)
$myvar = $foo + 1.3; // $myvar is now a float (3.3)
$myvar = 5 + "10 Piglets"; // $foo is integer (15)

PHP Variables Complement

Some functions are defined in php to help us work better with variables. You have known some from previous lessons and the important new ones are introduced in this lesson:

empty($Variable): Do you remember ‘isset()’ function? It returned us whether a variable is set or not; you can check the reverse by ‘empty($variable)’ function. If $variable (can be every kind of variables) is empty, null or isn’t set, this function returns ‘true’ or ‘1’.

gettype($Varible): Returns the variable type.

settype($Varible, “type”): Set the variable type to the $type and returns true if it is done successfully.

is_int($Variable): Returns ‘True’ if the variable type is ‘Integer’.

is_bool($Variable): Returns ‘True’ if the variable type is ‘Boolean’.

is_string($Variable): Returns ‘True’ if the variable type is ‘String’.

is_float($Variable): Returns ‘True’ if the variable type is ‘Float’.

is_numeric($Variable): Returns ‘True’ if the variable is numeric variable or a ‘string’ that can be changed to a number (such as “123b” that can be 123).

strval ($Variable): Return a ‘string’ value from the variable (or change the variable value to the ‘string’).

var_export($Variable): Prints the variable values without changing the type (i.e. it doesn’t change ‘true’ value to 1)

Note that we can use an expression inside the parenthesis instead of a variable.

Understanding Scope of a variable in PHP

The scope of a variable is the context within which it is defined. Basically you can not access a variable which is defined in different scope.

Next, we ‘re going to understand the scope of a variable in PHP. It’s very important to know the variable and its scope in a PHP program. The basic idea of this scope variable in PHP is to focus on where and how to define a variable and use it in context. The main point is to understand the limitations and extensions of defining a  variable and its use. See, the following explanation may help avoid confusion between the different types of use of variable scope variables in your code.

Types of Variables in PHP :

  1.  Local Variables
  2. Function variables or parameters
  3. Global Variables
  4. Static Variables

1. Local Variable :

A variable declared in a function is considered local. That is, it can be referenced only in that function. Any assignment outside of that function will be considered to be an entirely different variable from the one contained in the function.

The following is the right example to understand a local variable in PHP.

function MyFunction()
$a = 10;
echo $a;
//call to function

Output: In the above example it returns 10 why because $a will take value of a function 10.

2. Function Parameters :

A function in variable is that which is defined within the parentheses of the function and are simply pass by values. See, the following example represents how to define a function in PHP.

function MyFunction($price)
$price = $price*20;
echo $price;
//call to function 

In the above example $price is a function parameter takes a value 40. The output it returns 800 in this program.

3. Global Variables :

A variable global is a quiet contrast to a local variable. It is usable in any part of the program. It needs explicit “global” keyword to convert a variable as global.

$value = 11;
function TestFunction()
global $value;
echo $value;

The above function is going to take value which is initialized outside of the function 11. It gives 10 as its output. The reason is using “global” keyword you can access a variable at any part of the program.

4. Static Variables :

When the function exits, the variables like local, function parameters, and global are destroyed. A static variable ‘s ability is that it can keep value thereof. You can simply convert a static variable using a keyword named “static.”

function TestFunction()
static $count = 1;
echo $count;
echo "<br/>";

Call to TestFunction() in the above program will give you incremented output.


Add a Comment

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


My name is Nohman Habib and I am a web developer with over 10 years of experience, programming in Joomla, Wordpress, WHMCS, vTiger and Hybrid Apps. My plan to start codingace.com is to share my experience and expertise with others. Here my basic area of focus is to post tutorials primarily on Joomla development, HTML5, CSS3 and PHP.

Nohman Habib

CEO: codingace.com

Request a Quote