Understanding Variables in PHP | PHP Tutorial

Variables in PHP, like in any other programming language, can be treated as a storage for some information. This information or data can be used later within a program by simply using that variable name.

Every language has it’s own way of declaring or storing variables.

Following are some naming conventions that needs to be followed while declaring variables –

– Variable names must start with $ sign followed by the name of variable.

– In PHP variable names can contain only alphanumeric characters, underscore and hyphen ( for example $first_name, $last-name, $number1 etc.)

– Variable names must start with underscore(_) or alphabet only. Numbers cannot be used at initial character in variable names.

– PHP is loosely typed language and there is no need to define the type of variable. PHP automatically analyse it using values.

– In PHP, variables are case-sensitive. For example – $var and $VAR are treated as two different variables.

Declaring variables in PHP

Following example shows how you can declare variables within your PHP code

 

In the above example, there are three variables

$var which contains string value Some Information.

$x which contains integer value i.e 5

$y which contains float value i.e. 3.25

All strings value must be assigned using quotes around them.

Output Variables

In PHP, the echo statement is most generally used to print variables in web pages.

In the following example you can see how to combine variables with other text –

Output

I love Coding Lessons!

Variable Scopes in PHP

Variables can be declared anywhere within the script in PHP.

The Scope of a variable defines the section or block of code where it can be used after declaration. There are generally three types of variable scopes in PHP –

  • global
  • local
  • static

Global Variables

Global variables can be accessed anywhere within the code. In order to access global variables within the function, we can use $GLOBALS[index], where index is the name of variable.

Global variables are generally declared outside any function.

Following example shows how to use global variables –

output

Variable a inside function is: Global
Variable a outside function is: Global

Local Variables in PHP

Local variables has very limited scope and can be accessed within a function only.

Local variables are generally declared within functions.

Author: Deepak Kumar

This is Deepak Kumar, founder of True Infosystems and of-course the chief content creator at CodingLessions.info. Started my carrier as a Freelancer and now a top-rated Freelancer at Upwork, delivered over 200 successful projects with highly positive user ratings and counting.