php variables and their scope

Learn PHP Variables & Scope

In this tutorial, we’ll discuss PHP variables in detail. You’ll learn the basics of PHP variables, how to declare PHP variables, rules to create PHP variables, how to output data from variables, and the scope of PHP variables.

Before you learn more details about PHP variables, we assume you understand the basic PHP syntax and know how to write code in PHP.


What are PHP variables?

The PHP variables are memory locations that store any type of data/information. This information may be a string, integer, float, boolean, null, or any other PHP-supported data type. We use these variables in web applications to output data when required.

How to create/declare PHP variables?

There are two parts of a PHP variable.

  1. Name of PHP variable
  2. Value of PHP variable

To define a PHP variable, we use the dollar sign ($) followed by the name of the variable, the assignment operator (=), and the value (string, integer, float, etc.) of the variable.

<?php

$variable_name = "This is the value of the variable.";

echo $variable_name;

?>

The above example defines a string value (character string) for the PHP variable $variable_name and outputs the following in the web browser.

This is the value of the variable.

Similarly, you can create variables in PHP with other most common data types such as integer, float, etc.

<?php

$variable_string = "Learn PHP variables"; // This is a character string.

$variable1 = 23; // This is an integer value.
$variable2 = 29; // This is an integer value.

$variable_float = 29.143; // This value is a floating point number.

echo $variable_string;
echo "<br>"; // inserts a line break.
echo $variable1;
echo "<br>"; // inserts a line break.
echo $variable2;
echo "<br>"; // inserts a line break.
echo $variable_float;

?>

The code above produces the following output in the web browser.

Learn PHP variables
23
29
29.143

PHP is a loosely typed language

Unlike other programming languages, PHP is a loosely typed language. This is so because you don’t have to explicitly tell the PHP about the type of data you are creating. PHP automatically analyzes the value assigned to the variable and associates a PHP-supported data type with that variable such as string, integer, float, boolean, etc.

In the examples above, you can see that we didn’t tell PHP about the type of data inside variables. We’ve just assigned the values to variables.

Because of this ability, it is also possible to mix strings with integers in PHP as you will see in the examples below.

Despite being a loosely typed language, you can still specify data types in PHP when a certain type of data is expected by using type declarations. We’ll discuss them later.

Rules to name PHP variables

We follow certain rules to name variables in PHP.

  1. A valid PHP variable starts with a dollar sign ($).
  2. The first character of a PHP variable name after the dollar sign must always be a letter (a-z, A-Z) or underscore (_), followed by any number of letters, numbers, or underscores. A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, _).
  3. Variable names in PHP cannot contain special symbols (%, *, -, etc).
  4. A PHP variable name cannot start with a number.
  5. The names of PHP variables are case-sensitive. For example, $coderounds, $Coderounds, and $coDerounds are all completely different PHP variables.
  6. The valid name of a PHP variable must not contain any spaces. For example, $first name is an invalid variable name. We should instead use underscore to separate variable names e.g. $first_name.

Valid PHP variable names

<?php

/* EXAMPLES OF VALID PHP VARIABLE NAMES */

$firstvariable = "PHP variables"; // starts with a letter.

$_firstvariable = 954; // starts with an underscore.

$second_variable = 586; // underscore separates the two names.

$secondvariable = 199.99; // no spaces found.

echo $firstvariable;
echo "<br>";
echo $_firstvariable;
echo "<br>";
echo $second_variable;
echo "<br>";
echo $secondvariable;

?>

In the above example, all PHP variable names are valid and give the following output in the web browser.

PHP variables
954
586
199.99

Invalid PHP variable names

<?php

/* EXAMPLES OF INVALID PHP VARIABLE NAMES */

$1variable = "PHP variables"; // starts with a number.

$-firstvariable = 954; // starts with a hyphen.

$second%variable = 586; // percentage symbol separates the two names.

$second variable = 199.99; // spaces found in variable name.

echo $1variable;
echo "<br>";
echo $-firstvariable;
echo "<br>";
echo $second%variable;
echo "<br>";
echo $second variable;
?>

In the above example, all PHP variable names are invalid and give the following parsing error in the web browser. None of the echo statements produced any output.

Parse error: syntax error, unexpected integer "1", expecting variable or "{" or "$" in D:\xampp\htdocs\helloworld\helloworld.php on line 10

How to get output from variables in PHP?

We use PHP “echo statement” to output data from variables. We can use multiple ways to display the output of variables.

<?php

/* Output data from PHP variables (character strings) */

$coderounds = "Coderounds.com";

echo "The $coderounds is great.";
echo "<br>";

echo "The " .$coderounds. " is great.";
echo "<br>";

echo 'The ' .$coderounds. ' is great.'; // No variable output inside single quotation marks.
echo "<br>";

/* Output data from PHP variables (integers) */

$coderounds = "Coderounds.com"; // character string

$coderounds_rank = 44; // integer value

$coderounds_rating = 34; // integer value

$coderounds_score = $coderounds_rank + $coderounds_rating; // sum of two variables

echo "The $coderounds total score is $coderounds_score.";
echo "<br>";

echo "The " .$coderounds. " total score is $coderounds_score.";
echo "<br>";

echo 'The ' .$coderounds. ' total score is ' .$coderounds_score. '.';

?>

The above example shows the following output in the web browser. You can see that all echo statements produce similar output, although we are using different ways of getting the output.

The Coderounds.com is great.
The Coderounds.com is great.
The Coderounds.com is great.
The Coderounds.com total score is 78.
The Coderounds.com total score is 78.
The Coderounds.com total score is 78.

The scope of PHP variables

The scope of a PHP variable decides if we can call/access that variable from the whole PHP script or within a specified location such as a PHP function.

PHP supports three different types of variable scopes.

  1. Global variable
  2. Local variable
  3. Static variable

The global scope of a PHP variable

As the word global is self-explanatory, a variable has a global scope if it can be called anywhere inside a whole PHP script, or from linked PHP files.

A global variable is declared outside a PHP function and can only be called outside the function.

<?php

include 'practice-code.inc.php'; // $coderounds is defined in this file.

$global_variable = 'The coderounds.com is global.';

/* The Global Scope of variable $global_variable
    which is defined in current file helloworld.php */

echo $global_variable;
echo "<br>";

/* The global scope of variable $coderounds which 
	is called from the file "practice-code.inc.php" */
	
echo "The $coderounds is great.";
echo "<br>";

?>

The above example clearly shows that the scope of $global_variable and $coderounds is global because they can be called anywhere inside the PHP script. The $coderounds is defined in the file “practice-code.inc.php” which is included at the beginning of the file “helloworld.php“. Then, we called $coderounds in the file “helloworld.php”, it displays the value assigned in the original file. The above code produces the following output in the web browser.

The coderounds.com is global.
The Coderounds.com is great.

The local scope of a PHP variable

In PHP, we declare variables inside PHP functions and use those variables specifically inside that function. We call such variables as local variables.

The scope of a local variable spans only inside the function in which we declare that variable. We cannot use a local variable outside a function.

<?php

/* function local_variable() is created 
   to test local variables */

function local_variable(){
	
	$local_var = "Coderounds.com"; // local variable declared inside function
	
	echo "The $local_var is a great resource.";
	
}

local_variable(); // function local_variable(); is called.

?>

The above code displays the following output in the web browser.

The Coderounds.com is a great resource.

Now, if we call the same local variable $local_var outside the PHP function, it generates a warning in the web browser.

<?php

/* function local_variable() is created 
   to test local variables */

function local_variable(){
	
	$local_var = "Coderounds.com"; // local variable declared inside function
	
	echo "The $local_var is a great resource.";
	
}

echo $local_var; // try to use local variable outside the PHP function

?>

PHP code in the above example generates the following warning in the web browser.

Warning: Undefined variable $local_var in D:\xampp\htdocs\helloworld\helloworld.php on line 19

Local variables with the same name

We can declare local variables with the same name inside different PHP functions. Both variables work fine because both variables have local scope only inside the specific function where we use them.

<?php

/* function local_variable() is created 
   to test local variables */

function local_variable(){
	
	$local_var = "Coderounds.com"; // local variable declared inside function
	
	echo "The $local_var is a great resource.<br>";
	
}

/* function local_variable2() is created 
   to test same name local variables */
function local_variable2() {
	
	$local_var = "Same name"; // same name local variable declared in this function
	
	echo "This variable has $local_var";
	
}

local_variable(); // function 1 called

local_variable2(); // function 2 called

?>

In the example above, you can see that a same-name local variable $local_var was declared inside two different functions. It parses correctly and produces the following output in the web browser.

The Coderounds.com is a great resource.
This variable has Same name

The global keyword in PHP variables

We can access a global variable only outside a PHP function. If we try to use a global variable inside a PHP function, it generates an error. What if we want to use a global variable inside a PHP function? This is where we use the global keyword before a variable name inside the function to make this variable a local variable.

<?php

$global_1 = "This is first global variable.";

$global_2 = "This is second global variable.";

/* function global_variable() is created to use above 
	declared global variables inside PHP function */

function global_variable(){
	
	global $global_1, $global_2; // use of global keyword to access global variables
	
	echo $global_1;
	echo "<br>";
	echo $global_2;
	
}

global_variable(); // the function global_variable() is called

?>

The code in the above example generates the following output in the web browser.

This is first global variable.
This is second global variable.

Remember that if we change the value of a global variable inside the PHP function after using the keyword global, the changed value will also be available outside the function when we call that function.

<?php

/* USE OF THE global KEYWORD TO ACCESS GLOBAL VARIABLES */

$global_1 = "This is first global variable.";

/* function global_variable() is created to use above 
	declared global variables inside PHP function */

function global_variable(){
	
	global $global_1; // use of global keyword to access global variables
	
	$global_1 = "First global variable value changed."; // changed the value of $global_1
	
	echo $global_1;
	
}

global_variable(); // the function global_variable() is called

?>

The code in the above example generates the following output in the web browser. You can see that the echo statement displays the changed value in the web browser.

First global variable value changed.

$GLOBALS[index] array in PHP

There is another way of using a global variable inside a PHP function. This is the use of $GLOBALS[index] array where the name of the variable replaces the index. This array stores all global variables used in a PHP script. We can use this array to access global variables inside PHP functions.

<?php

/* USE OF THE $GLOBALS[index] array TO ACCESS GLOBAL VARIABLES */

$global_1 = 336; // global variable 1
$global_2 = 751; // global variable 2

/* function global_variable() is created to use above 
	declared global variables inside PHP function */

function global_variable(){

	$addition = $GLOBALS['global_1'] + $GLOBALS['global_2']; // use of $GLOBALS array to access global variables
	
	echo "The sum of two global variables is equal to " .$addition;
	
}

global_variable(); // the function global_variable() is called

?>

The above code displays the following output in the web browser.

The sum of two global variables is equal to 1087

Static variables in PHP

When we call a function, PHP deletes all its variables after the successful execution of that function.

What if we don’t want to delete the variable after the completion of the function? Suppose, we want to use the value of the variable again when we call the same function the next time.

We use the static keyword before the variable inside a PHP function to make it static. PHP doesn’t delete static variables even after the successful completion of the function and retains its value in the memory.

Remember that the static variable is still a local variable and we cannot use it outside the function.

/* USE OF THE static VARIABLES IN PHP */

function static_variable(){

	static $static_var = 91; // static variable declared
	$nonstatic_var = 91; // non-static variable declared
	
	$static_var++; // static variable incremented
	$nonstatic_var++; // non-static variable incremented
	
	echo "The value of static variable is " .$static_var;
	echo "<br>";
	echo "The value of non-static variable is " .$nonstatic_var;
	
}

static_variable(); // the function is called first time

?>

In the example above, you can see that when we call the function static_variable() the first time, it gives the following output in the web browser. See that both variables give the same output.

The value of static variable is 92
The value of non-static variable is 92

However, when we call the function static_variable() the second time, the output of the static variable changes. This is because the PHP retains the value of the variable $static_var the first time the function was called in the script and increments its value when we call the function a second time.

/* USE OF THE static VARIABLES IN PHP */

function static_variable(){

	static $static_var = 91; // static variable declared
	$nonstatic_var = 91; // non-static variable declared
	
	$static_var++; // static variable incremented
	$nonstatic_var++; // non-static variable incremented
	
	echo "The value of static variable is " .$static_var;
	echo "<br>";
	echo "The value of non-static variable is " .$nonstatic_var;
	echo "<br>";
}

static_variable(); // the function is called the first time
static_variable(); // the function is called the second time
static_variable(); // the function is called the third time

?>

The following output from the above code clearly shows that both variables give the same output when we call the function the first time. But, both variables differ in the output when we call the function the second time. Similarly, when we call the function the third time, the value of the static variable increments further.

Non-static variable $nonstatic_var clears its memory after each function call but the static variable $static_var retains its memory after each successful function call and increments further the next time the function is called.

The value of static variable is 92
The value of non-static variable is 92
The value of static variable is 93
The value of non-static variable is 92
The value of static variable is 94
The value of non-static variable is 92

PHP Superglobals

These are built-in and pre-defined variables that are always available in all scopes either local or global.

$GLOBALS, the variable we used earlier is also a superglobal variable.

Other superglobals include $_SERVER, $_GET, $_POST, $_FILES, $_COOKIE, $_SESSION, $_REQUEST, and $_ENV. We’ll discuss these superglobals in detail when we learn advanced PHP.

Similar Posts

Leave a Reply

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