1. PHP Variables Basics

1.1. What are PHP Variables?

PHP variables are used to store data similar to other programming languages. Usually, the PHP variables store data in the form of numbers, text, etc. In short, they are similar to boxes, to store data in it. Additionally, below are some essential characteristics of PHP variables, that need to be understood.

  • Firstly, PHP variables begin with a dollar sign $ followed by a name
  • Secondly, there is no need to declare the type of a variable in PHP, before storing data in it
  • Hence, PHP is a loosely typed language
  • Thus, PHP automatically declares a data type of a variable
  • Importantly, the assignment operator = helps in assigning the data to the variable
  • Moreover, the variable name must start with a letter or an underscore (_)
  • Also, a number cannot be at the start of a variable name
  • Therefore, a variable name can only start with letters and underscore only
  • Furthermore, PHP variables must contain numbers, letters and underscores only (A-z, 0-9 and _)
  • Most importantly, variables are case sensitive, means $name and $Name are different
  • Also, no spaces are allowed in variable names
  • Further, 08 data types can be assigned to a variable
  • Lastly, a PHP variable name can be of single character length $x to undefined length

Tutorial Contents:

  1. What are Basics of PHP Variables?
  2. How Can We Define / Declare Variables in PHP?
  3. What are the Scopes of PHP Variables?
  4. How to Declare a Variable Variable in PHP?
  5. use of Reference Method to Declare PHP Variables
  6. What are Different Variable Handling Functions in PHP?

2. How to Declare/Define a Variable in PHP?

Variables are declared in PHP with the help of an assignment operator =. See the example below to understand how to define or declare or create a PHP variable?

Example

<?php
/* Declaring PHP Variables */
$name = ‘John’;
$age = 40;

echo $name .’ is ‘.$age.’years old.’;
?>

In the above example, the two PHP variables $name and $age are declared. Further, note that the $name variable is a string, whereas, $age variable is a number.

2.1. Valid and InValid Variable Declaration

Variable Declarations

Below are some valid and invalid variable declarations.
<?php
/* Valid and InValid PHP Variable Declaration */

$name = ‘John’;  /*valid*/
$Name = “John”;  /*valid*/
$_country = ‘United States’;  /*valid*/
$_1age = 40;  /*valid*/
$1age = 40;  /*Invalid*/
$age$ = 30;  /*Invalid*/
$age+country = 30;  /*Invalid*/
?>

Note:

As in the above example, the variable $name has a string value in single quotes. Whereas, the variable $Name has a string value in double-quotes. Therefore, this indicates that both variable declarations are valid.

2.2. PHP Variables Output

There are several ways to output the data of a PHP variable. Consider the following example to comprehend this vividly.

PHP Variable Output

<?php
/* PHP Variable Output */
$tutorial = ‘PHP Variable Tutroial’;
$a = 100;
$b = 200;

echo “1-I am learning $tutorial”;
echo ‘2-I am learning $tutorial’;
echo ‘3-I am learning ‘. $tutorial;
echo ‘4-‘.($a + $b);
?>

In the above example, the PHP echo statement is used to display the variables data. Also, the first, third, and fourth statements showed variable value accurately.

  1. The first statement uses variable inside double quotes and displays the output as needed.
  2. The second statement uses a variable within single quotes and displays the variable name rather than variable value.
  3. The third statement comprises the variable outside the quotes with a dot (.) in between the string and variable. This is called a PHP concatenation operator that is used to join two strings.
  4. Ultimately, the fourth statement added the values of two variables simply.

Output

1-I am learning PHP Variable Tutorial
2-I am learning $tutorial
3-I am learning PHP Variable Tutorial
4-300

2.3. Predefined PHP Variables

Also, there are many predefined PHP variables known as reserved variables. Below is a list of Predefined PHP variables:

Predefined Variables
$GLOBALS References all variables available in the global scope
$_SERVER Server and execution environment information
$_GET HTTP GET variables
$_POST HTTP POST variables
$_FILES HTTP File Upload variables
$_REQUEST HTTP Request variables
$_SESSION Session variables
$_ENV Environment variables
$_COOKIE HTTP Cookies
$php_errormsg The previous error message
$HTTP_RAW_POST_DATA Raw POST data
$http_response_header HTTP response headers
$argc The number of arguments passed to script
$argv The array of arguments passed to script

3. PHP Variables Scope

Most importantly, a variable scope determines the limits of a PHP variable, where it can be utilized. Precisely, a variable scope is a domain where a variable is defined. Importantly, all variables have a single scope in PHP. There are three distinct PHP variable scopes.

  1. Local PHP Variable Scope
  2. Global PHP Variable Scope
  3. Static PHP Variable Scope

3.1. Local PHP Variable Scope

Local variable scope implies any variable that is defined within the curly braces of a function. Hence, this variable is exclusively available to that specific function. Analyze the below example to understand local PHP variable scope:

Local Variable Example

<?php
/* A local PHP variable is defined in a function and utilized */
function pie(){
  $country = ‘Canada’;  /* local scope variable */
  echo “John lives in $country.
“;
}
pie();
echo “Miller also lives in $country.”;
?>

Importantly, the second statement does not display the variable value as the variable has a local scope.

Output

John lives in Canada.
Miller also lives in .Missing output of $country

3.2. Global PHP Variable Scope

Whenever, a PHP variable is defined outside of a function, it has a global variable scope. Thus, that variable is not available within the function. However, in the C++ language, this global variable is also available within the function.

Global Variable Example

<?php
/* A global PHP variable is defined in a function and utilized */
$age = 20; /* global scope variable */
function pie(){
  echo “My age is $age.”;
}
pie();
?>

In the above example, the variable is declared globally and accessed locally. Hence, the variable will not display its value.

Output

My age is . /Missing Output of $age variable

Access Global Variable As Local Variable

However, certain methods permit the user to access the globally defined variable within the function. These include the global modifier and predefined $GLOBALS array.

a. The global Modifier

Firstly, PHP allows the use of a global modifier to access a global scope variable within a function. Hence, any number of global scope variables are easily accessed within a function by using this technique.

global Modifier Example

<?php
$x1 = 20; /* global scope variable */
$x2 = 30; /* Another global variable */
$y;
function addition(){
  global $x1, $x2, $y;
  $y = $x1 + $x2;
  echo “The Addition of $x1 and $x2 is equal to $y.”;
}
addition();
?>

Output

The addition of 20 and 30 is equal to 50.

b. The Predefined $GLOBALS Array

Secondly, PHP has a predefined $GLOBALS array to store all the global variables. It has a syntax as $GLOBALS[index]. The index is the name of variable and is used to access a global variable within a function. It is because $GLOBALS is a superglobal variable. Let’s look at the following example to understand.

$GLOBALS Array Example

<?php
$x1 = 20; /* global scope variable */
$x2 = 30; /* Another global variable */
$y;
function addition(){
  $GLOBALS[’y’] = $GLOBALS[’x1’] + $GLOBALS[’x2’];
  echo “The sum is ” . $GLOBALS[’y’];
}
addition();
?>

Output

The sum is 50

3.3. Static PHP Variable Scope

Furthermore, PHP has a third type of variable named as static scope variable. They use a static modifier to make a variable static and are only available within a local function. They keep the variables alive, as normally variables are destroyed after a function is executed. Let’s look at the following example to understand:

Example 1

<?php
/* A static scope variale is defined and utilised. */

function johnDeposit(){
  static keyword is used in this example
  static $a = 0; /* John deposits 100$ in his account every month */
  $a = $a + 100;
  echo “John’s deposits are $a$.\n”;
}
johnDeposit();
johnDeposit(); 
?>

Output

John’s deposits are 100$.
John’s deposits are 200$.

Example 2

<?php
/* A static scope variale is defined and utilised. */

function johnDeposit(){
  static keyword is not used in this example
  $a = 0; /* John deposits 100$ in his account every month */
  $a = $a + 100;
  echo “John’s deposits are $a$.\n”;
}
johnDeposit();
johnDeposit(); 
?>

Output

John’s deposits are 100$.
John’s deposits are 100$.

Now, the above two examples explain the importance of a static modifier. In the first example, the static modifier changed the local scope variable to a static scope variable. Hence, each time the function is called, the variable retained its new value. Whereas, in the second example, there is no static keyword. Thus, the variable $a displayed the same value each time the function is called.

4. Variable Variable

Sometimes, it is desirable or convenient to have a variable with changing name or variable variable name. Specifically, the new variable will takes the value of the variable as the name of the variable. This is done by putting a dollar sign before the variable i.e. a variable name with a double dollar sign. Let’s look at the following illustration:

Example

/* A variable variable name */
<?php
$x = ‘Jenny’;
$$x = ‘is our new student.’; this means $$x = $Jenny; 
echo “$x ${$x} Let’s welcome $x together.”;
?>

Output

Jenny is our new student. Let’s welcome Jenny together.

In the above example, $x is the first variable and has a value “Jenny”. The additional dollar sign before $x as $$x means that $$xx = $Jenny. Thus, the value of the first variable $x is used as a variable name in the second variable.

5. PHP Variable Declaration By Reference

There is another way to declare a PHP variable through a reference. Therefore, the value of a variable is obtained by using another variable. Also, this variable reference method uses an ampersand &, before the variable. This ampersand (&) assigns the value of one variable to another variable. Moreover, variables are not pointers like in the “C” language.
Furthermore, three different operations can be performed using PHP variable references.

  1. Assign By Reference
  2. Return By Reference
  3. Pass By Reference

The subsequent example distinctly shows, how to assign PHP variable values by reference?

PHP Variable References

<?php
/* PHP Variable Declaration by Reference */
$PHPTutorials = ‘This is a PHP variable Tutorial.’;
$tuts = &$PHPTutorials; /* A symbol ampersand(&) is used to assign value */
echo $tuts;
?>

Output

This is a PHP variable Tutorial.

6. PHP Variable Handling Function

Lastly, PHP has some predefined functions to manipulate variables. These functions are called variable handling functions. There is no need of any installation to access these variable handling functions. The table below contains all the variable handling functions.

Variable Handling Functions
Function Short Description
boolval() Returns the boolean value of a variable
debug_zval_dump() Dumps the string representation of and internal zend value to output
floatval() Returns the float value of a variable
doubleval() Alias of floatval()
empty() Checks whether a variable is empty or not
get_defined_vars() Returns an array of all defined variables
get_resource_type() Returns the type of a resource
gettype() Shows the type of variable
inval() The integer value of a variable is returned
is_array() To check if a variable is an array
is_bool() To check if a variable is a boolean
is_callable() It analyze the ontents of a variable to check whether thy can be called as function or not
is_countable() It checks if the contents of a variable are countable
is_float() Checks if the variable is of float type
is_double() Alias of is_float()
is_real() Alias of is_float()
is_int() Checks if the variable type is integer
is_integer() Alias of is_int()
is_long() Alias of is_int()
is_iterable() It checks if the variable value is iterable or not
is_null() To check if the variable is NULL
is_numeric() Used for checking if the variable is number or numeric string
is_object() To check if the variable is an object
is_resource() To check if the variable is a resource
is_scalar() It checks if the variable is scalar
is_string() Checks if the variable type is string
isset() This function checks if the variable is declared (i.e. not NULL)
print_r() Prints the variable related information as readily available for humans
serialize() To convert the storalbe representation of a variable
settype() To vonvert the variable type to some specific type
strval() It returns the string value of a variable
unserialize() Converts back the serialized data
unset() Unset or undeclare a variable
var_dump() It dumps information about variables
var_export() Returns the structured information about variables
Give Us Your Feedback
OR
If You Need Any Help!
Contact Us