PHP Variables: Declaration, Types, Rules and Examples

PHP Variables: A Complete Guide to Declaring, Using, and Understanding Variables in PHP

PHP variables are one of the most important building blocks of PHP programming. They allow developers to store, manage, and manipulate information such as names, numbers, prices, dates, user inputs, and other types of data. Whether you are building a simple PHP script, a dynamic website, a login system, or a database-driven application, understanding variables is essential.

PHP is a server-side scripting language that uses variables to store information temporarily while a program is running. These variables can hold different types of values, including strings, integers, floating-point numbers, Boolean values, arrays, and objects.

In this comprehensive guide, you will learn what PHP variables are, how to declare and use them, the rules for naming variables, variable types, variable scope, and common mistakes beginners should avoid.

What Are PHP Variables?

A variable in PHP is a named storage location used to hold data that can be accessed and modified throughout a program.

For example, if you want to store a person’s name, age, or email address, you can create variables and assign values to them.

PHP variables begin with the dollar sign ($), followed by the variable name.

Example:

<?php
$name = "John";
$age = 25;
$city = "New York";

echo $name;
echo $age;
echo $city;
?>

Output:

John25New York

In this example:

  • $name stores a string value.
  • $age stores an integer value.
  • $city stores another string value.
  • echo displays the values on the webpage.

Unlike some programming languages, PHP does not require you to declare a variable’s data type before assigning a value. PHP automatically determines the variable type based on the assigned value.

How to Declare Variables in PHP

Declaring a variable in PHP is simple. You only need to write a dollar sign ($), provide a variable name, and assign a value using the assignment operator (=).

Syntax:

$variable_name = value;

Here:

  • $ indicates that the identifier is a PHP variable.
  • variable_name is the name of the variable.
  • = assigns a value to the variable.
  • value represents the information stored in it.
  • ; ends the PHP statement.

Example:

<?php
$website = "VastPedia";
$visitors = 5000;
$price = 99.50;

echo $website;
echo "<br>";
echo $visitors;
echo "<br>";
echo $price;
?>

Output:

VastPedia
5000
99.5

You can assign different types of values to variables without specifying their data types.

Rules for Naming PHP Variables

PHP has specific rules for naming variables. Following these rules helps prevent syntax errors and makes your code easier to understand.

The main rules are:

  1. Every PHP variable must begin with a dollar sign ($).
  2. A variable name must start with a letter or an underscore (_) after the dollar sign.
  3. A variable name cannot begin with a number.
  4. Variable names can contain letters, numbers, and underscores.
  5. Variable names cannot contain spaces.
  6. Variable names are case-sensitive.
  7. PHP reserved keywords should not be used as variable names.

Examples of valid and invalid variable names:

Variable nameValid or InvalidExplanation
$nameValidStarts with a letter
$_nameValidStarts with an underscore
$user123ValidContains numbers
$first_nameValidContains an underscore
$123nameInvalidStarts with a number
$first nameInvalidContains a space
$user-nameInvalidContains a hyphen
$@emailInvalidContains an unsupported character

Example:

<?php
$firstName = "David";
$lastName = "Smith";
$user_age = 28;

echo $firstName;
echo "<br>";
echo $lastName;
echo "<br>";
echo $user_age;
?>

Using meaningful variable names is a good programming practice. For example, $studentName is more descriptive than $x.

PHP Variables Are Case-Sensitive

PHP variable names are case-sensitive. This means that uppercase and lowercase letters are treated as different characters.

For example, $name, $Name, and $NAME are three different variables.

Example:

<?php
$name = "John";
$Name = "David";
$NAME = "Michael";

echo $name;
echo "<br>";
echo $Name;
echo "<br>";
echo $NAME;
?>

Output:

John
David
Michael

Even though these variable names contain the same letters, PHP treats them as separate variables.

Therefore, maintain consistent capitalization throughout your PHP programs to avoid unexpected errors.

Assigning Values to PHP Variables

You can assign values to PHP variables using the assignment operator (=).

Example:

<?php
$website = "VastPedia";
$year = 2026;
$rating = 4.8;
$is_active = true;

echo $website;
echo "<br>";
echo $year;
echo "<br>";
echo $rating;
echo "<br>";
echo $is_active;
?>

PHP automatically identifies the data type based on the assigned value.

You can also change a variable’s value whenever necessary.

Example:

<?php
$color = "Red";

echo $color;

$color = "Blue";

echo "<br>";
echo $color;
?>

Output:

Red
Blue

The second assignment replaces the original value stored in $color.

Types of Values Stored in PHP Variables

PHP supports several data types that can be stored in variables. These data types determine what kind of information a variable can contain.

The most commonly used PHP data types include:

Data TypeDescriptionExample
StringStores text"Hello"
IntegerStores whole numbers100
FloatStores decimal numbers10.50
BooleanStores true or falsetrue
ArrayStores multiple values[10, 20, 30]
ObjectStores object instancesnew MyClass()
NULLRepresents no valuenull
ResourceHolds a reference to an external resourceFile or database resource

Let’s understand the most common variable data types with examples.

1. String Variables

A string variable stores text, characters, words, or sentences. In PHP, strings can be written inside single or double quotation marks.

Example:

<?php
$name = "John";
$message = 'Welcome to PHP Programming';

echo $name;
echo "<br>";
echo $message;
?>

Output:

John
Welcome to PHP Programming

Strings are commonly used for storing usernames, email addresses, website names, messages, and other text-based information.

2. Integer Variables

An integer variable stores whole numbers without decimal points. These numbers can be positive, negative, or zero.

Example:

<?php
$age = 25;
$students = 150;
$temperature = -5;

echo $age;
echo "<br>";
echo $students;
echo "<br>";
echo $temperature;
?>

Output:

25
150
-5

Integer variables are useful for counting records, storing ages, tracking quantities, and performing mathematical calculations.

3. Float Variables

A float variable, also called a floating-point variable, stores numbers containing decimal points.

Example:

<?php
$price = 99.99;
$height = 5.8;
$percentage = 85.75;

echo $price;
echo "<br>";
echo $height;
echo "<br>";
echo $percentage;
?>

Output:

99.99
5.8
85.75

Float variables are useful for calculations involving prices, measurements, percentages, and scientific values.

4. Boolean Variables

A Boolean variable stores one of two possible values: true or false.

Example:

<?php
$is_logged_in = true;
$is_admin = false;

var_dump($is_logged_in);
var_dump($is_admin);
?>

Output:

bool(true)
bool(false)

Boolean variables are commonly used in conditional statements, authentication systems, permission checks, and logical operations.

5. Array Variables

An array variable stores multiple values inside a single variable. This makes it easier to organize and manage related information.

Example:

<?php
$fruits = ["Apple", "Banana", "Orange"];

echo $fruits[0];
echo "<br>";
echo $fruits[1];
echo "<br>";
echo $fruits[2];
?>

Output:

Apple
Banana
Orange

Array indexing starts from zero in a standard indexed array.

PHP supports indexed arrays, associative arrays, and multidimensional arrays.

6. Object Variables

An object variable stores an instance of a class. Objects are used in object-oriented programming to organize data and functionality.

Example:

<?php
class Student {
    public $name = "John";
    public $age = 20;
}

$student = new Student();

echo $student->name;
echo "<br>";
echo $student->age;
?>

Output:

John
20

Objects are useful for developing large applications that require reusable and structured code.

7. NULL Variables

A NULL variable represents a variable with no value. You can assign null to a variable when you want to indicate that it currently contains no data.

Example:

<?php
$address = null;

var_dump($address);
?>

Output:

NULL

NULL is different from an empty string ("") or zero (0).

Displaying PHP Variable Values

PHP provides several ways to display the contents of variables. The most commonly used methods are echo, print, var_dump(), and print_r().

Using echo

The echo statement displays one or more strings or values.

Example:

<?php
$name = "John";
$age = 25;

echo $name;
echo "<br>";
echo $age;
?>

Using print

The print statement also displays output. Unlike echo, it returns a value of 1.

Example:

<?php
$message = "Learning PHP Variables";

print $message;
?>

Using var_dump()

The var_dump() function displays detailed information about a variable, including its data type and value.

Example:

<?php
$name = "VastPedia";
$age = 25;
$price = 99.50;

var_dump($name);
var_dump($age);
var_dump($price);
?>

Output:

string(9) "VastPedia"
int(25)
float(99.5)

This function is especially useful when debugging PHP programs.

Using print_r()

The print_r() function displays human-readable information about a variable, particularly arrays and objects.

Example:

<?php
$colors = ["Red", "Green", "Blue"];

print_r($colors);
?>

Output:

Array
(
    [0] => Red
    [1] => Green
    [2] => Blue
)

PHP Variable Scope

Variable scope refers to the area of a PHP program where a variable can be accessed.

PHP mainly supports four types of variable scope:

  1. Local variables
  2. Global variables
  3. Static variables
  4. Superglobal variables

Understanding variable scope is important because a variable declared in one part of a program may not be accessible from another part.

1. Local Variables

A local variable is declared inside a function and can only be accessed within that function.

Example:

<?php
function myFunction() {
    $message = "Hello PHP";
    echo $message;
}

myFunction();
?>

Output:

Hello PHP

In this example, $message is a local variable because it is declared inside the function.

Trying to access $message outside the function will not work because its scope is limited to that function.

2. Global Variables

A global variable is declared outside a function. By default, it cannot be accessed directly inside a function.

You can use the global keyword to access a global variable inside a function.

Example:

<?php
$name = "John";

function showName() {
    global $name;
    echo $name;
}

showName();
?>

Output:

John

Another way to access global variables inside a function is through the $GLOBALS array.

Example:

<?php
$website = "VastPedia";

function displayWebsite() {
    echo $GLOBALS['website'];
}

displayWebsite();
?>

The $GLOBALS array provides access to global variables by their names.

3. Static Variables

A static variable is declared inside a function using the static keyword. Unlike ordinary local variables, a static variable retains its value between function calls.

Example:

<?php
function counter() {
    static $count = 0;

    $count++;

    echo $count;
    echo "<br>";
}

counter();
counter();
counter();
?>

Output:

1
2
3

Without the static keyword, the variable would be initialized again whenever the function is called.

Static variables are useful for counters, tracking function calls, and retaining information between function executions.

4. Superglobal Variables

Superglobal variables are built-in PHP variables that can be accessed from anywhere in a script, including inside functions.

PHP provides several superglobal variables for handling user input, server information, sessions, cookies, and other application data.

SuperglobalPurpose
$GLOBALSAccesses global variables
$_SERVERProvides server and request information
$_GETCollects data sent through URL parameters
$_POSTCollects data submitted through HTTP POST requests
$_FILESHandles uploaded files
$_REQUESTCollects request data from GET, POST, and COOKIE
$_SESSIONStores session information
$_COOKIEAccesses cookie data
$_ENVProvides environment variables

Example using $_SERVER:

<?php
echo $_SERVER['PHP_SELF'];
?>

This displays the filename of the currently executing script.

Example using $_GET:

<?php
$name = $_GET['name'] ?? 'Guest';

echo "Welcome " . htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
?>

If the URL is:

example.com/index.php?name=John

The output will be:

Welcome John

Using htmlspecialchars() helps prevent HTML injection when displaying user-provided text.

Assigning Multiple Variables in PHP

PHP allows you to assign values to multiple variables in a single statement by using chained assignments.

Example:

<?php
$a = $b = $c = 100;

echo $a;
echo "<br>";
echo $b;
echo "<br>";
echo $c;
?>

Output:

100
100
100

All three variables receive the same value.

You can also assign different values to variables using separate statements.

<?php
$name = "David";
$age = 30;
$country = "India";

echo "$name is $age years old and lives in $country.";
?>

PHP Variables and the Assignment Operator

The assignment operator (=) assigns a value to a variable. PHP also provides compound assignment operators that make updating variable values easier.

OperatorExampleEquivalent Expression
=$x = 10Assigns 10 to $x
+=$x += 5$x = $x + 5
-=$x -= 5$x = $x - 5
*=$x *= 5$x = $x * 5
/=$x /= 5$x = $x / 5
%=$x %= 5$x = $x % 5
.=$x .= " PHP"$x = $x . " PHP"

Example:

<?php
$number = 10;

$number += 5;
echo $number;

echo "<br>";

$number *= 2;
echo $number;
?>

Output:

15
30

Compound assignment operators are useful when performing calculations or updating stored information.

PHP Variables and String Concatenation

PHP uses the dot (.) operator to combine strings and variable values.

This process is called string concatenation.

Example:

<?php
$firstName = "John";
$lastName = "Smith";

$fullName = $firstName . " " . $lastName;

echo $fullName;
?>

Output:

John Smith

You can also use double-quoted strings to insert variables directly into a string.

Example:

<?php
$name = "David";
$website = "VastPedia";

echo "Hello $name, welcome to $website.";
?>

Output:

Hello David, welcome to VastPedia.

Variable interpolation works inside double-quoted strings and heredoc strings, but not inside single-quoted strings.

PHP Variable Variables

PHP supports a feature called variable variables. It allows the name of one variable to be used as the name of another variable.

In other words, the value of a variable can determine the name of another variable.

Example:

<?php
$name = "website";

$$name = "VastPedia";

echo $website;
?>

Output:

VastPedia

Here, $name contains the text "website". Using $$name creates a variable named $website.

Variable variables can be useful in certain dynamic programming situations, but they should be used carefully because they can make code difficult to understand and maintain.

PHP Constants vs Variables

PHP variables and constants both store information, but they behave differently.

A variable’s value can be changed during program execution, whereas a constant’s value cannot be changed after it has been defined.

Example of a variable:

<?php
$website = "VastPedia";

$website = "Example";

echo $website;
?>

Output:

Example

Example of a constant:

<?php
define("SITE_NAME", "VastPedia");

echo SITE_NAME;
?>

Output:

VastPedia

Here is a comparison between PHP variables and constants.

FeatureVariablesConstants
SymbolStarts with $No $ when accessed
ValueCan be changedCannot be redefined
DeclarationAssignment operatordefine() or const
NamingCase-sensitiveCase-sensitive by default
ScopeDepends on declarationAvailable throughout the script after declaration
UsageStores changeable dataStores fixed configuration values

Constants are useful for storing information such as website names, application settings, and fixed configuration values.

Checking Variable Types in PHP

PHP provides built-in functions that help developers identify the data type of a variable.

Some commonly used functions include:

FunctionPurpose
gettype()Returns the variable’s data type as a string
is_string()Checks whether a variable is a string
is_int()Checks whether a variable is an integer
is_float()Checks whether a variable is a float
is_bool()Checks whether a variable is Boolean
is_array()Checks whether a variable is an array
is_object()Checks whether a variable is an object
is_null()Checks whether a variable is NULL
is_numeric()Checks whether a value is numeric or a numeric string

Example:

<?php
$name = "John";
$age = 25;
$price = 99.99;

echo gettype($name);
echo "<br>";

echo gettype($age);
echo "<br>";

echo gettype($price);
?>

Output:

string
integer
double

PHP commonly reports floating-point values as double through gettype().

You can also check whether a variable is a specific type.

<?php
$age = 25;

if (is_int($age)) {
    echo "Age is an integer.";
}
?>

Output:

Age is an integer.

Converting Variable Data Types in PHP

PHP allows developers to convert one data type into another. This process is called type casting.

For example, you can convert a string containing a number into an integer or a floating-point number.

Example:

<?php
$number = "100";

$integerNumber = (int) $number;
$floatNumber = (float) $number;

var_dump($integerNumber);
var_dump($floatNumber);
?>

Output:

int(100)
float(100)

Common PHP type casting operators include:

Casting OperatorConverts Value Into
(int)Integer
(float)Float
(string)String
(bool)Boolean
(array)Array
(object)Object
(unset)NULL in older PHP usage; deprecated since PHP 7.2

You can also use functions such as intval(), floatval(), and strval() for type conversion.

Example:

<?php
$price = "250";

$convertedPrice = intval($price);

echo $convertedPrice;
?>

Output:

250

Type conversion is useful when working with form inputs, database values, and mathematical calculations.

PHP Variables in HTML Forms

PHP variables are frequently used to collect and process information submitted through HTML forms.

For example, you can create a simple form that accepts a user’s name and displays a personalized greeting.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>PHP Variables Form</title>
</head>
<body>

<form method="POST">
    <label>Enter Your Name:</label>
    <input type="text" name="username" required>

    <button type="submit">Submit</button>
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $username = $_POST["username"] ?? "";

    echo "Welcome " .
        htmlspecialchars($username, ENT_QUOTES, 'UTF-8');
}
?>

</body>
</html>

When a user submits the form, PHP collects the submitted value and stores it in the $username variable.

The htmlspecialchars() function ensures that user-provided text is safely displayed as HTML text.

For applications that store or process important information, you should also validate and sanitize user input according to its intended use.

PHP Variables in Practical Applications

Variables are used in almost every PHP application. They help developers manage information and build dynamic website features.

Here are some common practical applications.

1. Storing User Information

<?php
$username = "John";
$email = "john@example.com";

echo "Username: $username";
echo "<br>";
echo "Email: $email";
?>

2. Performing Mathematical Calculations

<?php
$price = 500;
$quantity = 3;

$total = $price * $quantity;

echo "Total Price: " . $total;
?>

Output:

Total Price: 1500

3. Creating Dynamic Website Content

<?php
$website = "VastPedia";
$year = 2026;

echo "Welcome to $website.";
echo "<br>";
echo "Copyright $year.";
?>

4. Checking Login Status

<?php
$isLoggedIn = true;

if ($isLoggedIn) {
    echo "Welcome back!";
} else {
    echo "Please log in.";
}
?>

Output:

Welcome back!

5. Managing Product Information

<?php
$productName = "Laptop";
$productPrice = 45000;
$stock = 10;

echo "Product: $productName";
echo "<br>";
echo "Price: ₹$productPrice";
echo "<br>";
echo "Available Stock: $stock";
?>

These examples demonstrate how PHP variables help create dynamic and interactive web applications.

Common Mistakes When Working with PHP Variables

Beginners sometimes make mistakes when declaring, assigning, and using PHP variables. Understanding these common issues can help you write better code.

1. Forgetting the dollar sign

Every PHP variable must start with $.

Incorrect:

name = "John";

Correct:

$name = "John";

2. Using spaces in variable names

PHP does not allow spaces inside variable names.

Incorrect:

$first name = "John";

Correct:

$first_name = "John";

3. Using a number at the beginning

A variable name cannot start with a number.

Incorrect:

$123user = "David";

Correct:

$user123 = "David";

4. Confusing uppercase and lowercase variables

PHP treats variable names as case-sensitive.

$name = "John";

echo $Name;

In this example, $Name is different from $name and is not automatically assigned the value "John".

5. Accessing local variables outside functions

Local variables cannot normally be accessed outside the function in which they are declared.

6. Using an undefined variable

Trying to access a variable before assigning a value can produce warnings or other unexpected behavior, depending on the PHP version and error-reporting configuration.

7. Confusing assignment and comparison operators

The = operator assigns a value, while == compares values.

<?php
$age = 25;

if ($age == 25) {
    echo "Age matched.";
}
?>

Using === performs a strict comparison of both value and data type.

Best Practices for Using PHP Variables

Writing clean and understandable PHP code is important for maintaining websites and applications. Follow these practices when working with variables:

  • Use meaningful variable names that describe the stored information.
  • Follow a consistent naming convention, such as camelCase or snake_case.
  • Avoid using unnecessary global variables.
  • Initialize variables before using them.
  • Use appropriate data types for different kinds of information.
  • Prefer strict comparisons (===) when checking values and types.
  • Avoid variable variables unless there is a clear reason to use them.
  • Validate user input before processing it.
  • Escape user-generated output when displaying it in HTML.
  • Avoid storing sensitive information in ordinary variables longer than necessary.
  • Use constants for configuration values that should not change.
  • Keep variable scope as limited as practical.

Following these practices makes PHP applications easier to understand, debug, secure, and maintain.

Frequently Asked Questions (FAQs)

1. What are variables in PHP?

Variables in PHP are named storage locations used to hold information such as text, numbers, arrays, and other data. They begin with the dollar sign ($) and can be used throughout a program according to their scope.

2. How do you declare a variable in PHP?

You can declare a variable by writing a dollar sign followed by a variable name and assigning a value using the = operator.

Example:

$name = "John";

3. Why do PHP variables start with a dollar sign?

PHP uses the dollar sign ($) to identify variables. It helps distinguish variables from other identifiers, such as function names, class names, and constants.

4. Are PHP variables case-sensitive?

Yes. PHP variable names are case-sensitive. For example, $name, $Name, and $NAME are treated as three different variables.

5. Do you need to declare variable types in PHP?

No. PHP automatically determines the data type of a variable based on the value assigned to it. However, PHP also supports type declarations in function parameters, return values, and class properties.

6. What are the main types of variables in PHP?

PHP supports variables containing strings, integers, floats, Booleans, arrays, objects, NULL values, and resources. The actual type depends on the value assigned to a variable.

7. What is the difference between local and global variables in PHP?

A local variable is declared inside a function and is generally accessible only within that function. A global variable is declared outside a function and can be accessed inside a function using the global keyword or $GLOBALS array.

8. What are superglobal variables in PHP?

Superglobal variables are built-in PHP variables that can be accessed from anywhere in a script. Examples include $_GET, $_POST, $_SERVER, $_SESSION, and $_COOKIE.

9. Can you change the value of a PHP variable?

Yes. PHP variables can be reassigned whenever necessary.

Example:

<?php
$color = "Red";
$color = "Green";

echo $color;
?>

Output:

Green

10. What is the difference between a PHP variable and a constant?

A variable can hold a value that changes during program execution, while a constant stores a value that cannot be changed after it has been defined.

11. What is a static variable in PHP?

A static variable is a variable declared inside a function using the static keyword. It retains its value between function calls instead of being reinitialized each time.

12. Which function is used to check the data type of a PHP variable?

The gettype() function returns the data type of a variable. You can also use var_dump() to display its type and value together.

Conclusion

PHP variables are an essential part of PHP programming because they allow developers to store, manage, modify, and display information dynamically. From simple text and numerical values to arrays and objects, variables make it possible to build interactive websites and powerful web applications.

Understanding variable declaration, naming rules, data types, scope, assignment operators, and type conversion provides a strong foundation for learning more advanced PHP concepts.

If you are starting with PHP, practice creating variables, changing their values, using them in functions, and processing HTML form data. Once you understand how PHP variables work, learning conditional statements, loops, functions, arrays, and database operations will become much easier.

Leave a Comment