PHP Variables

La Lakshmi Priya Updated 17 Oct 2026
11 min read ·Lesson 20 of 248

What Is a Variable?

In simple terms: A variable is a named container that stores a value so you can use it later. You can think of it as a labeled box: the label is the variable's name, and the content is its value.

Technically: A variable is a name bound to a value stored in memory. In PHP, the name always begins with a dollar sign ($). PHP tracks the value's type automatically, and the same variable can hold values of different types at different times.

Why Variables Are Needed

Programs work with data that is not known when the code is written: a user's name, a product price from the database, the number of items in a cart, the current date. Variables let you:

  • Store values that are calculated or received at runtime
  • Reuse a value in many places without repeating it
  • Change a value as the program runs
  • Give meaning to data through descriptive names ($cartTotal instead of 2450)

Creating a Variable

Syntax

$variableName = value;
PartMeaning
$Marks the start of a variable name. Required every time the variable is used.
variableNameThe identifier you choose
=The assignment operator — stores the value on the right in the variable on the left
valueAny value or expression: a number, text, a calculation, a function call
;Ends the statement

Example

<?php
$studentName = "Priya";
$age = 21;
$feePaid = 15000.50;
$isEnrolled = true;

echo "$studentName is $age years old.";

Output

Priya is 21 years old.

How It Works

  • PHP has no separate "declare" step. A variable is created the first time a value is assigned to it.
  • $studentName holds a string, $age an integer, $feePaid a float (decimal number), and $isEnrolled a boolean (true or false).
  • You never state the type. PHP determines it from the value. This is called dynamic typing.
  • Inside double-quoted strings, variables are replaced by their values. This is called interpolation and is explained in String Interpolation.

Important: = means assign, not "is equal to". $age = 21 stores 21 in $age. Comparing values uses == or ===, covered in Comparison Operators.


Rules for Variable Names

RuleValidInvalid
Must start with $$totaltotal
First character after $ must be a letter or underscore$name, $_temp$1name
Remaining characters: letters, digits, underscores$item2, $order_id$order-id, $order id
Names are case-sensitive$Total and $total are different—
$this is reserved—$this = 5; (fatal error)

What Happens With an Invalid Name

<?php
$first-name = "Ravi";
PHP Parse error:  syntax error, unexpected token "=" in /path/script.php on line 2

PHP reads $first-name as $first - name (a subtraction), and you cannot assign a value to the result of a subtraction. Use $firstName or $first_name instead.

Naming Conventions

PHP itself does not enforce a style, but consistent naming makes code much easier to read:

  • camelCase — $orderTotal, $isLoggedIn (common in modern PHP and frameworks such as Laravel and Symfony)
  • snake_case — $order_total (common in WordPress and older codebases)

Choose one style per project. Name booleans so they read as yes/no questions: $isActive, $hasDiscount, $canEdit.


Using and Changing Variables

A variable's value can be read as often as needed and replaced at any time.

Example

<?php
$stock = 50;
echo "Opening stock: $stock\n";

$stock = $stock - 12;   // 12 items sold
echo "After sales: $stock\n";

$stock = $stock + 30;   // new delivery
echo "After delivery: $stock\n";

Output

Opening stock: 50
After sales: 38
After delivery: 68

How It Works

In $stock = $stock - 12;, PHP first evaluates the right side using the current value (50 − 12 = 38), then stores the result back into $stock, replacing the old value. The old value is gone; a variable holds one value at a time.

Shorter compound assignment operators do the same thing: $stock -= 12; and $stock += 30;. These are covered in Assignment Operators.


Variables Can Change Type

Because PHP is dynamically typed, a variable can hold a value of one type and later a value of another type.

Example

<?php
$value = 42;
var_dump($value);

$value = "forty-two";
var_dump($value);

$value = 4.2;
var_dump($value);

$value = null;
var_dump($value);

Output

int(42)
string(9) "forty-two"
float(4.2)
NULL

Understanding var_dump()

var_dump() prints a variable's type and value, which makes it the most useful tool for inspecting variables while learning and debugging:

OutputMeaning
int(42)Integer with value 42
string(9) "forty-two"String, 9 bytes long, with the value in quotes
float(4.2)Floating-point number
bool(true)Boolean
NULLNo value

echo only prints the value and hides the type. For example, echo "42"; and echo 42; look identical, but var_dump() shows string(2) "42" versus int(42). When a comparison or calculation behaves unexpectedly, var_dump() usually reveals that a value has a different type than you assumed.

Should You Change a Variable's Type?

PHP allows it, but it is rarely a good idea. Code where $price is sometimes a number and sometimes text is hard to reason about. Keep each variable to one meaning and one type. Modern PHP adds type declarations for function parameters, return values, and properties so that PHP can enforce types where it matters; see Type Declarations in Functions and Strict Types.


Outputting Variables

There are several ways to output a variable inside text.

Example

<?php
$product = "Headphones";
$price = 1999;

// 1. Interpolation in double quotes
echo "The $product costs ₹$price.\n";

// 2. Concatenation with the dot operator
echo 'The ' . $product . ' costs ₹' . $price . ".\n";

// 3. Curly-brace interpolation (clear boundaries)
echo "Buy 2 {$product}s today.\n";

Output

The Headphones costs ₹1999.
The Headphones costs ₹1999.
Buy 2 Headphoness today.

How It Works

  1. Double quotes replace variable names with values.
  2. Single quotes do not interpolate, so the string pieces are joined with . (the concatenation operator). "\n" is in double quotes because escape sequences such as \n also work only in double quotes.
  3. Curly braces mark exactly where the variable name ends. Without them, "$products" would look for a variable named $products, which does not exist.

(The plural "Headphoness" shows that interpolation is purely mechanical — PHP inserts the value exactly as it is.)


Undefined Variables

What Happens

Reading a variable that has never been assigned produces a warning, and PHP uses null as its value.

<?php
$quantity = 3;

echo "Total items: " . $quantiy;

Output

PHP Warning:  Undefined variable $quantiy in /path/script.php on line 4
Total items: 

Why It Matters

The typo $quantiy creates a reference to a completely different, non-existent variable. The script continues running with an empty value, which can lead to wrong calculations, empty fields in emails, or incorrect data saved to a database. Since PHP 8.0 this is a warning (it used to be a notice), which is easier to notice — but only if error reporting is enabled during development.

Prevention:

  • Enable error_reporting = E_ALL and display_errors = On in development.
  • Use an editor with PHP support; it underlines undefined variables as you type.
  • Initialize variables before using them, even when the first value is 0, '', or [].

Checking and Removing Variables

isset() — Does the Variable Exist and Is It Not Null?

<?php
$username = "admin";
$email = null;

var_dump(isset($username));
var_dump(isset($email));
var_dump(isset($phone));

Output

bool(true)
bool(false)
bool(false)
  • $username exists and is not null → true.
  • $email exists but is null → false.
  • $phone was never created → false, and no warning is raised.

isset() is the standard way to check optional data, such as form fields that may not have been submitted.

unset() — Destroy a Variable

<?php
$token = "abc123";
unset($token);

var_dump(isset($token));

Output

bool(false)

After unset(), the variable no longer exists. It is commonly used to remove items from arrays or to release a large value no longer needed in a long-running script. In a typical web request, all variables are destroyed automatically when the request ends, so unset() is rarely needed just to free memory.

empty() — Does the Variable Have an "Empty" Value?

empty() returns true when a variable does not exist or its value is falsy: 0, 0.0, "0", "", null, false, or [].

<?php
$discountCode = "";
$itemsInCart = 0;

var_dump(empty($discountCode));
var_dump(empty($itemsInCart));

Output

bool(true)
bool(true)

Be careful: empty("0") is true. If a user enters 0 as a valid answer — for example, the number of children in a form — empty() treats it as "no value". The PHP Form Required lesson discusses safer checks.


Assignment by Value and by Reference

By Value (the Default)

When you assign one variable to another, PHP copies the value. The two variables are independent afterward.

<?php
$original = 100;
$copy = $original;

$copy = 500;

echo "Original: $original, Copy: $copy";

Output

Original: 100, Copy: 500

Changing $copy does not affect $original. This applies to arrays too: assigning an array creates an independent copy. (PHP optimizes this internally with copy-on-write — the actual copying happens only when one of the variables is modified — so assigning large arrays is cheap.)

By Reference (&)

Adding & makes the second variable another name for the same value.

<?php
$original = 100;
$alias = &$original;

$alias = 500;

echo "Original: $original, Alias: $alias";

Output

Original: 500, Alias: 500

Both names now point to one value, so changing either one changes both.

When to Use References

References are used in specific situations, such as modifying array elements inside a foreach loop or letting a function change its caller's variable (see Pass by Reference). In everyday code, assignment by value is clearer and safer, because changes cannot have surprising effects elsewhere.

Note: Objects behave differently. Assigning an object to another variable copies a handle to the same object, so both variables refer to the same object even without &. This is explained in the PHP OOP section.


Practical Example: A Simple Invoice

<?php
$customer = "Lakshmi Traders";
$invoiceNumber = "INV-2026-0142";

$itemName = "Office Chair";
$unitPrice = 4500;
$quantity = 6;
$taxRate = 0.18;

$subtotal = $unitPrice * $quantity;
$taxAmount = $subtotal * $taxRate;
$grandTotal = $subtotal + $taxAmount;

echo "Invoice: $invoiceNumber\n";
echo "Customer: $customer\n";
echo "Item: $itemName x $quantity\n";
echo "Subtotal: ₹" . number_format($subtotal, 2) . "\n";
echo "GST (18%): ₹" . number_format($taxAmount, 2) . "\n";
echo "Grand total: ₹" . number_format($grandTotal, 2) . "\n";

Output

Invoice: INV-2026-0142
Customer: Lakshmi Traders
Item: Office Chair x 6
Subtotal: ₹27,000.00
GST (18%): ₹4,860.00
Grand total: ₹31,860.00

How It Works

  • Input variables ($unitPrice, $quantity, $taxRate) store the raw data. In a real application, these would come from a form or database.
  • Calculated variables ($subtotal, $taxAmount, $grandTotal) store intermediate results. Naming each step makes the calculation self-documenting and easy to verify.
  • number_format($value, 2) formats a number with two decimal places and thousands separators. It returns a string, so it is used only for display, while the numeric variables remain available for further calculations.
  • $taxRate is stored once. If the rate changes, only one line needs editing.

Common Mistakes

Forgetting the $

<?php
$total = 500;
echo total;

Result: Fatal error: Uncaught Error: Undefined constant "total". Without $, PHP treats total as a constant name.

Fix: Always write $total.

Typos in Variable Names

Result: Warning: Undefined variable, and the value is treated as null.

Fix: Keep error reporting on during development and rely on editor warnings.

Confusing = With ==

<?php
$role = "user";

if ($role = "admin") {
    echo "Access granted";
}

Result: Access granted is printed. $role = "admin" assigns "admin" to $role, and the assignment expression evaluates to "admin", which is truthy. The condition is always true, and $role has been overwritten.

Fix: Use === to compare: if ($role === "admin").

Single Quotes When Interpolation Is Expected

<?php
$name = "Asha";
echo 'Hello, $name';

Result: Hello, $name — single-quoted strings print variable names literally.

Fix: Use double quotes or concatenation: "Hello, $name" or 'Hello, ' . $name.

Using empty() When 0 Is a Valid Value

Result: Valid input such as 0 or "0" is treated as missing.

Fix: Check explicitly, for example isset($value) && $value !== ''.


Best Practices

  • Use descriptive names that explain the meaning of the value: $monthlyRevenue, not $mr.
  • Keep one consistent naming style (camelCase or snake_case) throughout a project.
  • Initialize variables before using them.
  • Keep each variable to a single purpose and type.
  • Store values that are used repeatedly (such as tax rates) in one variable or constant.
  • Use var_dump() to inspect types while debugging, and remove debug output before deploying.
  • Prefer assignment by value; use references only when you specifically need shared modification.

Official reference: https://www.php.net/manual/en/language.variables.basics.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else User-defined Functions Slicing Strings Function Arguments PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery $_SESSION $_ENV PHP RegEx RegEx Patterns Heredoc and Nowdoc RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures Composer PHP Form Handling PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro PHP Class Constants Encryption with Sodium Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS What Is `$_SERVER` ? $_REQUEST $_POST $_GET $_FILES $_COOKIE PHP Type Juggling MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PSR-4 Autoloading Installing Extensions (PECL / PIE) OPcache & Performance PHP-FPM Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Shopping Cart with Sessions Project: REST API with PHP DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files
Ask about this post
AI Ask about this post

Ask questions about PHP Variables and get answers drawn from it.

Signed-in readers only.