PHP Variables: A Complete Guide for Beginners with Examples

Last updated 4 months ago | 290 views 75     5

Tags:- PHP

Introduction: Why PHP Variables Matter

If you're new to PHP (or any programming language), the first building block you'll encounter is the variable. Think of variables as containers that store data—like names, numbers, or even entire arrays.

In PHP, variables allow you to store, reuse, and manipulate data efficiently throughout your application. Whether you're collecting form input, displaying a user's name, or performing calculations—you’re using variables.

Let’s break down everything you need to know about PHP variables in a practical, beginner-friendly way.


✍️ What Is a Variable in PHP?

In PHP, a variable starts with a dollar sign $, followed by the variable name.

<?php
$name = "Vinay";  // A string variable
$age = 30;        // An integer variable
?>

Variables are loosely typed, meaning you don't need to declare the data type explicitly.


Declaring Variables in PHP

✅ Basic Syntax

$variable_name = value;
  • Always starts with $

  • Must begin with a letter or underscore

  • Cannot start with a number

  • Case-sensitive ($Name$name)

✅ Example:

<?php
$city = "Delhi";
$temperature = 39.5;
?>

PHP Variable Types

PHP automatically converts variables based on context (dynamic typing). Here are the common types:

Type Example Description
String $name = "John"; Text enclosed in quotes
Integer $age = 25; Whole number
Float $price = 10.99; Decimal number
Boolean $isActive = true; true or false
Array $colors = array("Red", "Blue"); Multiple values in a single variable
NULL $data = NULL; Empty variable

Variable Scope in PHP

1. Global

Available outside functions.

$site = "StudyZone4U";

function showSite() {
    global $site; // Makes the global variable accessible
    echo $site;
}

2. Local

Defined within a function and only accessible there.

function showMessage() {
    $message = "Hello!";
    echo $message;
}

3. Static

Retains its value between function calls.

function counter() {
    static $count = 0;
    $count++;
    echo $count;
}

Working with Variables: Examples

✅ String Concatenation

$firstName = "John";
$lastName = "Doe";

echo "Full Name: " . $firstName . " " . $lastName;

✅ Arithmetic with Variables

$price = 100;
$tax = 18;

$total = $price + $tax;
echo "Total Amount: ₹" . $total;

Complete Example: Putting It All Together

<?php
// Define some variables
$name = "Alice";
$age = 28;
$skills = array("PHP", "HTML", "CSS");

// Create a function that uses global variable
$platform = "StudyZone4U";
function welcomeMessage() {
    global $platform;
    echo "Welcome to " . $platform . "!<br>";
}

// Display user info
function showProfile($name, $age, $skills) {
    echo "Name: $name<br>";
    echo "Age: $age<br>";
    echo "Skills:<br>";
    foreach ($skills as $skill) {
        echo "- $skill<br>";
    }
}

// Call functions
welcomeMessage();
showProfile($name, $age, $skills);
?>

⚠️ Tips & Common Pitfalls

✅ Tips:

  • Use meaningful names: $userName is better than $x.

  • Stick to lowercase or camelCase ($userEmail) for consistency.

  • Initialize variables to avoid undefined variable errors.

  • Comment tricky logic to improve readability.

❌ Common Mistakes:

  • Forgetting the $ sign: name = "John";

  • Using variables before defining them

  • Mixing up variable case sensitivity

  • Overwriting global variables unintentionally inside functions


Conclusion: Think in Variables

Understanding variables in PHP is essential for everything from printing text to handling forms and managing databases. Once you're comfortable using variables, you're ready to tackle conditions, loops, and more advanced PHP concepts.


Takeaways:

  • Variables in PHP start with a $ and are dynamically typed.

  • Use clear, descriptive variable names for maintainable code.

  • Master scope rules to avoid unexpected bugs.

  • Practice with different types: strings, numbers, arrays, booleans.