PHP Variables

Storing and managing data in PHP

📦 PHP Variables

Variables are containers for storing data values. In PHP, variables start with a dollar sign ($) followed by the variable name. They can hold text, numbers, arrays, and more.


<?php
$name = "John";
echo "Hello, $name!";
?>
                                    

Output:

Hello, John!

Variable Basics

$

Dollar Sign

All PHP variables must start with a dollar sign ($). This tells PHP that you're working with a variable, not a keyword or function.

<?php
$age = 25;
$name = "Alice";
?>
Aa

Case Sensitive

Variable names are case-sensitive. $name, $Name, and $NAME are three different variables. Always use consistent naming throughout your code.

<?php
$name = "John";
$Name = "Jane";
// Different variables!
?>
🔤

Naming Rules

Variable names must start with a letter or underscore, followed by letters, numbers, or underscores. No spaces or special characters allowed except underscore.

<?php
$user_name = "Valid";
$_temp = "Valid";
$user2 = "Valid";
?>
🔄

Dynamic Typing

PHP automatically determines the data type based on the value. You don't need to declare types. Variables can change types during execution.

<?php
$var = "text";
$var = 123; // Now a number
?>

🔹 Creating Variables

How to declare and assign values to variables:


<?php
// Creating variables with different data types

// String (text)
$name = "Alice";
$city = 'New York';

// Integer (whole number)
$age = 25;
$quantity = 100;

// Float (decimal number)
$price = 19.99;
$temperature = 98.6;

// Boolean (true/false)
$isActive = true;
$hasDiscount = false;

// Display the variables
echo "Name: $name<br>";
echo "City: $city<br>";
echo "Age: $age<br>";
echo "Price: $$price<br>";
echo "Active: " . ($isActive ? "Yes" : "No");
?>
                            

Output:

Name: Alice
City: New York
Age: 25
Price: $19.99
Active: Yes

🔹 Variable Naming Conventions

Best practices for naming variables:

✅ Valid Variable Names:

<?php
$userName = "Valid";      // camelCase
$user_name = "Valid";     // snake_case (common in PHP)
$_private = "Valid";      // Starting with underscore
$user2 = "Valid";         // Numbers allowed (not at start)
$UserName = "Valid";      // PascalCase
?>

❌ Invalid Variable Names:

<?php
$2user = "Invalid";       // Can't start with number
$user-name = "Invalid";   // Hyphens not allowed
$user name = "Invalid";   // Spaces not allowed
$user@name = "Invalid";   // Special characters not allowed
?>

💡 Recommended Naming Style:

  • Use descriptive names: $userAge instead of $a
  • Use snake_case: $first_name (common in PHP)
  • Use camelCase: $firstName (also popular)
  • Be consistent: Pick one style and stick with it

🔹 Variable Scope

Understanding where variables can be accessed:

🔸 Local Scope


<?php
function myFunction() {
    $localVar = "I'm local";
    echo $localVar;  // Works inside function
}

myFunction();
// echo $localVar;  // ERROR: Not accessible outside function
?>
                            

🔸 Global Scope


<?php
$globalVar = "I'm global";

function showGlobal() {
    global $globalVar;  // Must declare as global
    echo $globalVar;
}

showGlobal();  // Outputs: I'm global
echo $globalVar;  // Also works outside function
?>
                            

🔸 Static Variables


<?php
function counter() {
    static $count = 0;  // Retains value between calls
    $count++;
    echo "Count: $count<br>";
}

counter();  // Count: 1
counter();  // Count: 2
counter();  // Count: 3
?>
                            

Output:

Count: 1
Count: 2
Count: 3

🔹 Variable Operations

Working with variables in different ways:


<?php
// Assignment
$x = 10;
$y = 20;

// Arithmetic operations
$sum = $x + $y;
$difference = $y - $x;
$product = $x * $y;
$quotient = $y / $x;

echo "Sum: $sum<br>";
echo "Difference: $difference<br>";
echo "Product: $product<br>";
echo "Quotient: $quotient<br>";

// String concatenation
$firstName = "John";
$lastName = "Doe";
$fullName = $firstName . " " . $lastName;
echo "Full Name: $fullName<br>";

// Increment/Decrement
$counter = 5;
$counter++;  // Now 6
$counter--;  // Back to 5
echo "Counter: $counter";
?>
                            

Output:

Sum: 30
Difference: 10
Product: 200
Quotient: 2
Full Name: John Doe
Counter: 5

🔹 Variable Variables

Using the value of one variable as the name of another:


<?php
// Variable variables (advanced concept)
$varName = "message";
$$varName = "Hello World!";

// Now $message exists with value "Hello World!"
echo $message;  // Outputs: Hello World!

// Practical example
$fruit = "apple";
$apple = "A delicious red fruit";

echo $$fruit;  // Outputs: A delicious red fruit
?>
                            

Output:

Hello World!A delicious red fruit

🔹 Checking Variables

Useful functions to check variable status:


<?php
$name = "Alice";
$age = 25;
$empty = "";

// isset() - Check if variable is set and not null
if (isset($name)) {
    echo "Name is set<br>";
}

// empty() - Check if variable is empty
if (empty($empty)) {
    echo "Variable is empty<br>";
}

// is_null() - Check if variable is null
$nullVar = null;
if (is_null($nullVar)) {
    echo "Variable is null<br>";
}

// var_dump() - Display variable information
var_dump($age);  // int(25)

// gettype() - Get variable type
echo "<br>Type: " . gettype($name);  // string
?>
                            

Output:

Name is set
Variable is empty
Variable is null
int(25)
Type: string

🔹 Practical Variable Example

A real-world example using variables:


<?php
// E-commerce product example

// Product information
$productName = "Wireless Headphones";
$regularPrice = 99.99;
$discountPercent = 20;
$quantity = 2;
$taxRate = 0.08;

// Calculate discount amount
$discountAmount = $regularPrice * ($discountPercent / 100);

// Calculate discounted price
$salePrice = $regularPrice - $discountAmount;

// Calculate subtotal
$subtotal = $salePrice * $quantity;

// Calculate tax
$taxAmount = $subtotal * $taxRate;

// Calculate final total
$total = $subtotal + $taxAmount;

// Display receipt
echo "<h3>Order Receipt</h3>";
echo "<p>Product: $productName</p>";
echo "<p>Regular Price: $$regularPrice</p>";
echo "<p>Discount: $discountPercent% (-$$discountAmount)</p>";
echo "<p>Sale Price: $$salePrice</p>";
echo "<p>Quantity: $quantity</p>";
echo "<p>Subtotal: $$subtotal</p>";
echo "<p>Tax (8%): $$taxAmount</p>";
echo "<p><strong>Total: $$total</strong></p>";
?>
                            

Output:

Order Receipt

Product: Wireless Headphones

Regular Price: $99.99

Discount: 20% (-$19.998)

Sale Price: $79.992

Quantity: 2

Subtotal: $159.984

Tax (8%): $12.79872

Total: $172.78272

🧠 Test Your Knowledge

What symbol must all PHP variables start with?