PHP Variables
Variables are containers for storing data values. In PHP, variables are incredibly flexible and easy to use - you don't need to declare their type, and they can hold any kind of data. Let's learn how to create and use variables effectively!
What Are Variables?
A variable is like a labeled box where you can store
information. You can put data in, take it out, change it, or use it in
calculations. In PHP, all variable names start with a dollar sign
($).
Click Run to execute your code
Variable Declaration
Creating a variable in PHP is simple - just use the $ symbol
followed by the variable name and assign a value:
<?php
// Syntax: $variableName = value;
$message = "Hello, PHP!";
$count = 42;
$price = 19.99;
$isActive = true;
?>
$count is an integer, $price is a float, etc.
Variable Naming Rules
PHP has specific rules for naming variables. Follow these to avoid errors:
| Rule | Example | Valid? |
|---|---|---|
| Must start with $ | $name |
โ Yes |
| Can contain letters, numbers, underscore | $user_123 |
โ Yes |
| Must start with letter or underscore (after $) | $_temp |
โ Yes |
| Cannot start with a number | $2name |
โ No |
| Case-sensitive | $Name โ $name |
โ Different variables |
| No spaces allowed | $first name |
โ No |
| No hyphens allowed | $first-name |
โ No |
Click Run to execute your code
Naming Conventions
While PHP is flexible, following naming conventions makes your code more readable and professional:
| Convention | Example | When to Use |
|---|---|---|
| camelCase | $firstName, $totalPrice |
Most common for variables |
| snake_case | $first_name, $total_price |
Alternative style, WordPress uses this |
| PascalCase | $FirstName |
Rarely used for variables |
| UPPER_CASE | $MAX_SIZE |
Constants only |
Variable Assignment
You can assign and reassign variables as many times as you want:
<?php
// Initial assignment
$count = 10;
echo $count; // Output: 10
// Reassignment
$count = 20;
echo $count; // Output: 20
// Change type (PHP allows this!)
$count = "twenty";
echo $count; // Output: twenty
?>
Variable Variables
PHP has a unique feature called "variable variables" - using the value of one variable as the name of another:
<?php
$varName = "message";
$$varName = "Hello!"; // Creates $message = "Hello!"
echo $message; // Output: Hello!
?>
Checking if Variable Exists
Use isset() to check if a variable has been set:
<?php
$name = "John";
if (isset($name)) {
echo "Variable exists!";
}
if (isset($age)) {
echo "This won't print";
}
?>
Unsetting Variables
Remove a variable from memory using unset():
<?php
$temp = "temporary data";
echo $temp; // Output: temporary data
unset($temp);
// $temp no longer exists
?>
Common Mistakes
1. Forgetting the dollar sign
<?php
name = "John"; // โ Error: undefined constant
$name = "John"; // โ
Correct
?>
2. Using reserved words
<?php
$class = "MyClass"; // โ 'class' is reserved
$className = "MyClass"; // โ
Better choice
?>
3. Case sensitivity confusion
<?php
$userName = "John";
echo $username; // โ Undefined variable (different case!)
echo $userName; // โ
Correct
?>
4. Using undefined variables
<?php
echo $undefinedVar; // โ Warning: undefined variable
// Better approach
if (isset($undefinedVar)) {
echo $undefinedVar;
} else {
echo "Variable not set";
}
?>
Exercise: Variable Practice
Task: Create a simple profile using variables!
Requirements:
- Create variables for: name, age, city, occupation
- Display them in a formatted message
- Calculate birth year from age (current year - age)
- Use proper naming conventions
Show Solution
<?php
// Profile variables
$fullName = "Jane Smith";
$age = 28;
$city = "San Francisco";
$occupation = "Software Developer";
// Calculate birth year
$currentYear = 2024;
$birthYear = $currentYear - $age;
// Display profile
echo "Profile Information:\n";
echo "Name: " . $fullName . "\n";
echo "Age: " . $age . "\n";
echo "City: " . $city . "\n";
echo "Occupation: " . $occupation . "\n";
echo "Born in: " . $birthYear;
?>
Summary
- Variables: Containers for storing data, start with
$ - Declaration:
$name = value;- no type needed - Naming: Letters, numbers, underscore; must start with letter or underscore
- Case-sensitive:
$nameand$Nameare different - Conventions: Use camelCase or snake_case consistently
- Flexible: Can change type and value anytime
- isset(): Check if variable exists
- unset(): Remove variable from memory
What's Next?
Now that you understand variables, it's time to explore Data Types! In the next lesson, you'll learn about the different types of data PHP can store - integers, floats, strings, booleans, arrays, and more.
Enjoying these tutorials?