PHP Variables

By Vijay

By Vijay

Image
I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.
Updated July 4, 2025
Edited by Kamila

Edited by Kamila

Image
Kamila is an AI-based technical expert, author, and trainer with a Master’s degree in CRM. She has over 15 years of work experience in several top-notch IT companies. She has published more than 500 articles on various Software Testing Related Topics, Programming Languages, AI Concepts,…

Learn about our editorial policies.

PHP Variables act as containers to store numeric & non-numeric information. Understand the concepts of PHP Variable creation, variable handling, variable scope, etc, with examples:

In this tutorial, you will learn what a PHP variable is, how to create PHP variables, $var vs $$var, PHP variable handling, PHP variable scope (local, global, and static variables), pre-defined variables such as superglobals, server variables, and frequently asked questions (FAQs).

=> Read Through the Series of PHP Tutorials

PHP Variable: Overview with Examples

PHP Variables

Please note that we have used PHP version 7 in all examples.

Let’s begin!

What is PHP Variable?

A PHP variable is used to store information. It acts as a container for storing both numeric and non-numeric information.

Example:

$color

$qty

$car = “BMW” (after assigning a non-numeric value)

$ref_num = 95 (after assigning a numeric value)

Rules for PHP Variables

The following list shows the rules for creating (declaring) variables:

  • A variable must start with the dollar sign ($), followed by the name of the variable.
  • A variable name must start with a letter or _ (the underscore character).
  • It cannot start with a number.
  • It can only contain alpha-numeric characters and _ (A-z, 0-9, and _).
  • It cannot contain any space.
  • Variable names are case-sensitive. For example, $NAME, $Name and $name are three different variables.
  • Some variable names are reserved.

Examples: $_POST, $_GET, etc.

The following table shows examples of valid and invalid variable names:

ValidInvalidInvalid Reason
1$birth_datebirth_dateNo leading $ sign
2$birthdate$birth-dateCannot contain –
3$Birthdate$birth dateCannot contain space
4$BirthDate$B’dayCannot contain ’
5$_birthdate#birthdateNo leading $
Cannot contain #
6$Year2000$ Year2000Cannot contain space
7$Year_2000$Year#2000Cannot contain #
8$x$1Cannot start with a number
9$cars30$30carsCannot start with a number
10$aBcD$#my_nameCannot contain #

How to Create PHP Variables

A variable must start with the dollar sign ($), followed by the variable name. The operator used for assigning a value to the variable is the assignment operator (=). We can use the echo statement to output variables (values).

PHP is a loosely typed language. Therefore, you don’t need to declare the type of the variable. Based on the variable value, PHP automatically converts the variable to the correct data type.

A few examples are shown below. You can practice these examples by running the following programming code:

Example 1:

<?php

$name = "John Doe ";
$age = 50;
 
echo $name; 
echo $age; 

?>

Output:

John Doe 50

After successful code execution, the $name variable will store the text value John Doe, and the $age variable will store the integer value 50.

Note: There are different methods to output variable values. In this tutorial, we use only the echo statement to output variables. In an upcoming tutorial, we will discuss other methods that can be used to output variables.

Example 2: Sum of two numbers

<?php

$num1 = 5;
$num2 = 10;

echo $num1 + $num2;

?>

Output:

15

Example 3: Concatenation

<?php

$city = "New Delhi";
$country = "India";

echo $city . " is the capital of ". $country . ".";

?>

Output:

New Delhi is the capital of India.

Example 4: Reusability

Once a variable is declared, you can reuse it.

Also, you can re-assign a variable to a new value. In such a case, the variable value is the most recently assigned value.

<?php

$num1 = 10;
$num2 = 50;

$num1 = 25;

echo $num1;

echo "<br>".$num1+ $num2 ; // num1=25 and num2=50

?>

Output:

25

75

$var vs $$var

You have already learned that $var is a (normal) variable. What about $$var?

Let’s find out!

In PHP, you can assign a variable to another variable by assigning the value of an existing variable as the name of the new variable. It is called a variable variable or dynamic variable. It contains two $ signs ($$).

The code below shows an example. You can practice this example by running the following programming code:

<?php

$txt = 'Hello';

$$txt = 'world';

echo "$txt ${$txt}";  

?>

Output:

Hello world

PHP Variable Handling

There are several functions to handle variables in PHP, as shown in the list below:

  1. boolval() – Output the boolean value of a variable.
  2. debug_zval_dump() – Display a string representation of an internal zval structure to output.
  3. doubleval() – Alias of floatval.
  4. empty() – Check whether or not a variable is empty.
  5. floatval() – Return the float value of a variable.
  6. get_debug_type() – Return the type name of a variable in a manner that’s appropriate for debugging.
  7. get_defined_vars() – Return a multidimensional array of all defined variables.
  8. get_resource_id() – Return an integer identifier for a resource.
  9. get_resource_type() – Return the type of the resource.
  10. gettype() – Return the type of a variable.
  11. intval() – Return the integer value of a variable.
  12. is_array() – Check whether or not a variable is an array.
  13. is_bool() – Check whether or not a variable is a boolean.
  14. is_callable() – Confirm that variable content can be called as a function.
  15. is_countable() – Confirm that variable content is a countable value.
  16. is_double() – Alias of is_float.
  17. is_float() – Check whether or not the type of a variable is float.
  18. is_int() – Check whether or not the type of a variable is an integer.
  19. is_integer() – Alias of is_int.
  20. is_iterable() – Confirm that the contents of a variable are an iterable value.
  21. is_long() – Alias of is_int.
  22. is_null()- Check whether or not a variable is null.
  23. is_numeric() – Check whether or not a variable is a number or a numeric string.
  24. is_object() – Check whether or not a variable is an object.
  25. is_real() – Alias of is_float.
  26. is_resource() – Check whether a variable is a resource or not.
  27. is_scalar() – Check whether a variable is a scalar or not.
  28. is_string() – Check whether a variable is a string or not.
  29. isset() – Check whether a variable is declared and is different than null.
  30. print_r() – Output information about a variable in a human-readable way.
  31. serialize() – Output a storable representation of a value.
  32. settype() – Set the variable type.
  33. strval() – Get the string value of a variable.
  34. unserialize() – Accept a single serialized variable and converts it back to a PHP value.
  35. unset() – Unset a given variable.
  36. var_dump() – Display structured information about a variable.
  37. var_export() – Outputs a parsable string representation of a variable.

The following table shows more details about the above functions:

FunctionSyntaxParameters
(Required / Optional)
Return Value TypeSupported PHP Version
1boolval() boolval (variable)variable – requiredboolean5.5.0+
2debug_zval_dump() debug_zval_dump (variable,…)variable – required
… – optional
4.2.0+
3empty() empty (variable)variable – requiredboolean4.0+
4floatval() floatval (variable)variable – requiredfloat4.2.0+
5get_debug_type() get_debug_type (variable)variable – requiredstring8
6get_defined_vars() get_defined_vars ()no parametersarray4.0.4+
7get_resource_id() get_resource_id (resource)resource – requiredinteger8
8get_resource_type() get_resource_type (resource)resource – requiredstring4.0.2+
9gettype() gettype (variable)variable – requiredstring4.0+
10intval() intval (variable, base)variable – required
base – optional
integer4.0+
11is_array() is_array (variable)variable – requiredboolean4.0+
12is_bool() is_bool (variable)variable – requiredboolean4.0+
13is_callable() is_callable (variable, syntax_only, name)variable – required
syntax_only – optional
name – optional
boolean4.0.6+
14is_countable() is_countable (variable)variable – requiredboolean7.3.0+
15is_float() is_float (variable)variable – requiredboolean4.0+
16is_int() is_int (variable)variable – requiredboolean4.0+
17is_iterable() is_iterable (variable)variable – requiredboolean7.1.0+
18is_null() is_null (variable)variable – requiredboolean4.0.4+
19is_numeric() is_numeric (variable)variable – requiredboolean4.0+
20is_object() is_object (variable)variable – requiredboolean4.0+
21is_resource() is_resource (variable)variable – requiredboolean4.0+
22is_scalar() is_scalar (variable)variable – requiredboolean4.0.5+
23is_string() is_string (variable)variable – requiredboolean4.0+
24isset() isset (variable, ….)variable – required
… – optional
boolean4.0+
25print_r() print_r (variable, return)variable – required
return – optional
true or string4.0+
26serialize() serialize (value)value – requiredstring4.0+
27settype() settype (variable, type)variable – required
type – required
boolean4.0+
28strval() strval (variable)variable – requiredstring4.0+
29unserialize() Unserialize (string, options)string – required
options – optional
boolean, integer, float, string, array or object4.0+
30unset() unset (variable, ….)variable – required
… – optional
4.0+
31var_dump() var_dump (variable, …)variable – required
… – optional
4.0+
32var_export() var_export (variable, return)variable – required
return – optional
mixed4.2.0+

Variable Scope

You can declare a variable anywhere in your code. However, the variable scope determines which part of the code can access it.

There are three variable scopes in PHP as listed below:

  1. Local
  2. Global
  3. Static

#1) Local Variable

Local variables are declared inside a function. They can be used by statements within that function only.

Let’s see an example. You can practice this example by running the following programming code:

<?php  

	function local_var() {  

		$num = 20;  //local variable  
		echo $num;  
		
	}  

	local_var();  

?>  

Output:

20

#2) Global Variable

Global variables are declared outside of all functions. They can be accessed by any function. Usually, global variables are declared at the top of the program.

The global keyword needs to be added before the variable to access the global variable within a function.

Let’s see an example. You can practice this example by running the following programming code:

<?php  

	$num = 20;  //global variable  

	function global_var() {  

		global $num; 
		 
		echo $num."</br>"; 
		
	}  

	global_var();  
	
	echo $num + 5; 

?>

Output:

20

25

#3) Static Variable

Usually, after function execution, all of its variables are deleted. However, sometimes we need a local variable to retain for further tasks. In such a case, you can add the static keyword when you first declare the variable.

Let’s see an example. You can practice this example by running the following programming code:

<?php  

	$num = 20;  //global variable  

	function static_var() {  

		static $num_1 = 10; //static variable
		$num_2 = 20; //non-static variable
		
		$num_1++; //increment of num_1
		$num_2++; //increment of num_2
		
		echo $num_1."</br>"; 
		echo $num_2."</br>"; 
		
	}  

	static_var(); //first function call
	static_var(); //second function call

?>

Output:

11
21
12
21

Predefined Variables

PHP has several predefined variables. They can be categorized into two main categories, as shown below:

  1. Superglobals
  2. Server variables

Note: You cannot use superglobals as variable variables inside a function or a class method.

Let’s discuss each of them in detail.

#1) Superglobals

Superglobals are a special set of variables. They are automatically global and available in all three scopes. Usually, superglobals are written in uppercase letters.

There are 9 superglobals in PHP, as shown in the list below:

  1. $GLOBALS – All variables available in the global scope
  2. $_SERVER – Web server environment information
  3. $_GET – HTTP GET variables
  4. $_POST – HTTP POST variables
  5. $_FILES – HTTP file uploads
  6. $_COOKIE – HTTP cookies
  7. $_SESSION – Session variables
  8. $_REQUEST – HTTP request variables
  9. $_ENV – Environment variables

Note: We will discuss most of the above superglobals in detail in upcoming tutorials.

#2) Server Variables

There are about 40 server variables in PHP, and some of them are listed below. You may refer to this link to find the full detailed list of server variables.

  1. $_SERVER[‘PHP_SELF’]
  2. $_SERVER[‘SERVER_NAME’]
  3. $_SERVER[‘SERVER_PROTOCOL’]
  4. $_SERVER[‘REQUEST_METHOD’]
  5. $_SERVER[‘REQUEST_TIME’]
  6. $_SERVER[‘HTTP_CONNECTION’]
  7. $_SERVER[‘HTTP_HOST’]
  8. $_SERVER[‘HTTPS’]
  9. $_SERVER[‘REMOTE_USER’]
  10. $_SERVER[‘PATH_INFO’]

Frequently Asked Questions

1. What are PHP variables?

In simple words, they are the containers used to store information.

2. How are variables declared in PHP?

They are declared using the dollar sign ($), followed by the variable name.
Examples: $country, $AUS, $num1

3. How are PHP variables used? Explain with an example.

When you consider the example, $age = 15; $age is the variable name, and this variable stores the integer value of 15. Usually, the echo keyword is used to output the variable value.

4. What is the main difference between $student and $$student?

Both are variables. But $student is a normal variable while $$student is a variable variable.

5. What do you mean by variable variables in PHP?

It is a variable that stores the value of an existing variable as its name.

6. What is a dynamic variable in PHP?

It is the same as the variable variables.

7. What are superglobals in PHP?

Superglobals are a set of predefined global variables. They have a global scope and no need to declare. Superglobals are $GLOBALS, $_SERVER, $_GET, $_POST, $_FILES, $_COOKIE, $_SESSION, $_REQUEST and $_ENV.

8. What do $GLOBALS, $REQUEST, and the global keyword do in PHP?

$GLOBALS is a PHP superglobal that returns all variables available in the global scope. PHP $_REQUEST is also a superglobal that gathers data after submitting a form (HTML form).
The global keyword is used to import variables from the global scope into the local scope of a function.

9. What are PHP server variables?

PHP $_SERVER variables are variables that return information about the web server environment.
Examples of server variables:
$_SERVER[‘SERVER_NAME’]
$_SERVER[‘PATH_INFO’]

10. What is a local variable and a global variable in PHP?

A local variable is a variable declared inside a function, while a global variable is defined outside a function.

Conclusion

Variables act as containers to store both numeric and non-numeric information. Each variable starts with the dollar sign ($), followed by its name. You can give dynamic names for variables too. PHP has several built-in functions for variable handling.

Furthermore, there are three variable scopes in PHP named local, global, and static. Superglobals and server variables are predefined variables in PHP.

PREV Tutorial | NEXT Tutorial

Was this helpful?

Thanks for your feedback!

READ MORE FROM THIS SERIES:



Leave a Comment