Web Analytics

PHP Variables

Beginner~25 min read

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 ($).

Output
Click Run to execute your code
Key Point: PHP is a loosely typed language. You don't need to tell PHP what type of data a variable holds - it figures it out automatically! The same variable can even hold different types at different times.

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;
?>
Pro Tip: Unlike some languages (like Java or C++), you don't need to declare the variable type. PHP automatically determines whether $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
Output
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
Important: Choose one convention and stick with it throughout your project. Mixing styles makes code harder to read!

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!
?>
Pro Tip: Variable variables are powerful but can make code confusing. Use them sparingly and only when they make your code clearer!

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: $name and $Name are 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.