Learn PHP Variables in detail

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

What is a variable?

A variable is a space in computer memory that has a name that is recognized and can contain some value for us, such as text, numbers, etc. Its like when you meet somebody at a park and ask him “What is your name?” and he replies with a name or with a weird look. In PHP, we can say that the name is the variable and the weird look is its NULL value (which means he has nothing), but here in PHP there are certain rules for 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 by PHP and the contents of them have been set by PHP and we can not change their values. They are called ‘Predefined Variables’. Their names start with ‘$_’ or ‘__’. We can also have variables in this format, but the name must not 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 start with a letter but not with any special character or a number. Of course, you can use an underscore (_) to define 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 into the variable is to put the variable name on the left, then use the ‘=’ 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 put the result into 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, 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 the ‘false’ value equals nothing or, in some cases, to 0. Another usage of this variable is to save a function’s returned value. If the answer comes from a function is ‘true’, the ‘true’ value will be saved in 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 a complex program and you are worried about whether you have ever used one variable name or set an initial value for it or not, you can use the ‘isset ($variable)’ function. The output of this function is’ true ’or’ false ’(1 or 0):


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

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

Another variable that we often see is the ‘integer’ variable. It covers a wide range of true numbers (32 or 64 bits) without any points 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 variable 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 the ‘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’, which is a float number like ‘Description: 0.3.’ So be careful with the last number (digit) of the results of your calculations.

And the other type of variable discussed here is the string, which consists of different characters which exist on 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 of defining 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, or you can do it backwards. Let’s start with 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 the 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 a 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 the type of variable. 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 the 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 the ‘isset (‘) function? It returns us whether a variable is set or not; you can check the reverse by using the ’empty ($variable)’ function. If $variable (can be any kind of variable) 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 return 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 a 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 a‘string’).

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

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

Understanding the 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 a different scope.

Next, we’re going to understand the scope of a variable in PHP. It’s very important to know the variables and their 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
  1. Function variables or parameters
  1. Global Variables
  1. 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 a variable is that which is defined within the parentheses of the function and is simply passed 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 the 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

PHP Code Snippets Powered By : XYZScripts.com