PHP Variables – A Beginner-Friendly Guide
In PHP, variables are used to store data like text, numbers, or other values. Let’s walk through the basics step by step.
1. Declaring Variables in PHP
- A variable always starts with a $ sign.
- The name comes right after $ without spaces.
Examples:
$firstname = 'Fazli';
$secondname = 'Hassan';
$price = 15;
Here:
$firstname
stores the string “Fazli”.
$price
stores the number 15.
2. Variables are Case-Sensitive
In PHP, uppercase and lowercase letters matter!
$firstname = 'Fazli';
$FirstName = 'Jacob';
👉 These are treated as two different variables because of the capital F in $FirstName
.
3. Rules for Variable Names
✅ Allowed:
- Letters (a–z, A–Z)
- Numbers (0–9) but not at the beginning
- Underscore _
❌ Not Allowed:
- Special symbols like -, @, !, etc.
- Starting with a number
Examples:
$var_name = 'Valid – underscore is fine';
$var_name2 = 'Valid – number allowed after first letter';
$var-name = '❌ Invalid – hyphen not allowed';
$2var_name = '❌ Invalid – cannot start with number';
4. Displaying Variables (Output)
The two most common ways to display variables in PHP are echo and print.
Using echo:
echo $firstname; // Outputs: Fazli
echo $price; // Outputs: 15
Using print:
print $firstname; // Outputs: Fazli
print $price; // Outputs: 15
🔎 Difference:
The echo
is slightly faster and can output multiple values at once.
The print
returns a value (1)
, so it can be used in expressions—but usually, beginners just use echo.
5. Variable Naming Conventions
When working in a team or writing clean code, it’s best to follow consistent naming conventions.
Common conventions in PHP:
✅ camelCase
First word lowercase, following words capitalized.
Example:
$firstName = 'Fazli';
$totalPrice = 100;
✅ snake_case
Words are separated by underscores.
Example:
$first_name = 'Fazli';
$total_price = 100;
✅ PascalCase (less common for variables, more for Classes)
Every word starts with a capital letter.
Example:
$FirstName = 'Fazli';
$TotalPrice = 100;
Quick Summary
- Variables start with $
- Case-sensitive (
$name ≠ $Name
) - Valid names can contain letters, numbers (not at start), and underscores
- Use echo or print to display values
✨ With these basics, you’re ready to start working with variables in PHP!