PHP Variables – Complete Beginner Tutorial
Variables are one of the most important concepts in PHP. Almost every PHP program uses variables to store information, perform calculations, display dynamic content, process forms, communicate with databases, and much more.
Without variables, every value would have to be typed manually into your code. Variables make programs flexible, reusable, and much easier to maintain.
What is a Variable?
A variable is simply a named container that stores information.
Think of a variable as a labelled storage box. Instead of remembering the actual value, your program remembers the label.
For example:
$name = "John";
Here:
- $name is the variable.
- John is the value stored inside it.
Later in the program you can use $name instead of writing “John” repeatedly.
Creating Variables
Variables in PHP always begin with the dollar sign ($).
<?php
$name = "John";
$city = "London";
$age = 30;
?>
You can now display them:
<?php
echo $name;
echo "<br>";
echo $city;
echo "<br>";
echo $age;
?>
Output:
John
London
30
How Variables Work
Imagine you own a travel company.
Instead of writing your company name hundreds of times, you could write:
$company = "Travel & Culture Services";
Whenever you need the company name:
echo $company;
If your business name changes, you only need to update it in one place.
Variable Naming Rules
PHP has a few simple rules.
| Rule | Example |
|---|---|
| Must begin with $ | $name |
| Must start with a letter or underscore | $city |
| Cannot begin with a number | $123name ❌ |
| Can contain numbers | $name1 ✔ |
| No spaces | $first_name ✔ |
| Case Sensitive | $name ≠ $Name |
Good Variable Names
Always choose meaningful names.
Good examples:
$customerName
$totalPrice
$productName
$emailAddress
$bookingDate
$hotelName
Poor examples:
$a
$b
$x
$temp1
$abc
$data2
Good names make your programs easier to understand months or even years later.
Changing Variable Values
A variable can be updated whenever needed.
<?php
$price = 100;
echo $price;
$price = 150;
echo "<br>";
echo $price;
?>
Output:
100
150
The second assignment replaces the first value.
Displaying Variables Inside Text
PHP can combine variables with normal text.
<?php
$name = "Alice";
echo "Welcome $name";
?>
Output:
Welcome Alice
You can also use curly braces to make complex strings easier to read.
echo "Welcome {$name}";
Multiple Variables
You can create as many variables as your application requires.
<?php
$firstName = "Ali";
$lastName = "Khan";
$country = "Pakistan";
$profession = "Developer";
echo $firstName;
echo "<br>";
echo $lastName;
echo "<br>";
echo $country;
echo "<br>";
echo $profession;
?>
Variables and Mathematics
Variables can store numbers and be used in calculations.
<?php
$price = 120;
$quantity = 4;
$total = $price * $quantity;
echo $total;
?>
Output:
480
Tip:
Variables are not limited to text or numbers. They can also store arrays, objects, dates, files, database records, and much more.
Variable Scope
The scope of a variable determines where it can be accessed within a PHP script.
PHP supports three main types of variable scope:
- Local Variables
- Global Variables
- Static Variables
Local Variables
A variable created inside a function is only available within that function.
<?php
function showName()
{
$name = "John";
echo $name;
}
showName();
?>
Output:
John
The variable $name cannot be accessed outside the function.
Global Variables
A variable created outside a function is known as a global variable.
<?php
$company = "Travel & Culture Services";
function displayCompany()
{
global $company;
echo $company;
}
displayCompany();
?>
Output:
Travel & Culture Services
The global keyword allows a function to access variables defined outside the function.
Static Variables
Normally, local variables disappear after a function finishes executing.
Static variables remember their values between function calls.
<?php
function counter()
{
static $count = 0;
$count++;
echo $count . "<br>";
}
counter();
counter();
counter();
?>
Output:
1
2
3
This feature is useful when tracking how many times a function has been executed.
Checking if a Variable Exists
PHP provides the isset() function.
<?php
$name = "Ali";
if(isset($name))
{
echo "Variable exists";
}
?>
Output:
Variable exists
Checking for Empty Variables
The empty() function checks whether a variable contains a value.
<?php
$name = "";
if(empty($name))
{
echo "Name is empty";
}
?>
Output:
Name is empty
Removing Variables
You can remove a variable using unset().
<?php
$name = "John";
unset($name);
?>
After calling unset(), the variable no longer exists.
Variable Variables
PHP supports a unique feature called variable variables.
<?php
$country = "Pakistan";
$Pakistan = "Beautiful Country";
echo $$country;
?>
Output:
Beautiful Country
This feature is powerful but should be used carefully because it can make code difficult to understand.
Type Juggling
PHP automatically converts data types when appropriate.
<?php
$number = "100";
$total = $number + 50;
echo $total;
?>
Output:
150
PHP automatically converts the string into a number.
Real World Example – Tour Booking System
Variables become extremely useful when building real applications.
<?php
$tourName = "Hunza Valley Tour";
$price = 950;
$days = 7;
echo "<h2>$tourName</h2>";
echo "<p>Duration: $days Days</p>";
echo "<p>Price: USD $price</p>";
?>
Output:
Hunza Valley Tour
Duration: 7 Days
Price: USD 950
Imagine managing hundreds of tours. Instead of manually editing every page, variables allow information to be generated dynamically from a database.
Common Beginner Mistakes
| Mistake | Correct Version |
|---|---|
| name = “John”; | $name = “John”; |
| $123name | $name123 |
| $Name and $name assumed equal | Variables are case-sensitive |
| Using undefined variables | Check using isset() |
Best Practices
- Use meaningful variable names.
- Keep naming consistent.
- Avoid single-letter variable names.
- Use camelCase or snake_case consistently.
- Initialize variables before using them.
- Check variables with isset() when necessary.
- Use comments when variable purpose is unclear.
Practice Exercises
- Create variables for your name, city and country.
- Display them using echo.
- Create two numeric variables and calculate their sum.
- Use isset() to verify a variable exists.
- Use empty() to check an empty variable.
- Create a simple tour package using variables.
Summary
Variables are the foundation of PHP programming. They allow you to store, manipulate and display data efficiently. Every PHP application, from a simple contact form to a large e-commerce website, depends heavily on variables.
You learned how to create variables, follow naming rules, update values, perform calculations, work with scope, check variable existence and apply variables in real-world situations.
Mastering variables is essential because nearly every future PHP topic builds upon this knowledge.
Frequently Asked Questions
Do all PHP variables start with $?
Yes. Every variable name in PHP begins with the dollar sign.
Are variable names case-sensitive?
Yes. $name and $Name are considered different variables.
Can variables store numbers and text?
Yes. Variables can store strings, integers, decimals, arrays, objects and many other data types.
What does isset() do?
It checks whether a variable exists and contains a value.
What does unset() do?
It removes a variable from memory.
Quick Challenge
Create a PHP page displaying information about a hotel package.
Store the following information in variables:
- Hotel Name
- City
- Price Per Night
- Number of Rooms
- Total Cost
Display the information using HTML generated by PHP.
Next Tutorial
Now that you understand variables, it is time to learn about the different types of data that variables can hold.
Next: PHP Data Types