✍️ PHP Basics
Estimated reading: 3 minutes 61 views

🧺 PHP Variables – Create, Assign, and Use Effectively

PHP variables are the foundation of dynamic programming. They are used to store and manipulate data, whether it’s text, numbers, or complex data structures like arrays and objects.

This guide will walk you through everything you need to know about PHP variables — how to declare, assign, and use them, as well as scoping, types, best practices, and real-world examples.


💡 What Are PHP Variables?

A variable in PHP is a symbolic name for storing data that can change during program execution. Variables in PHP are always prefixed with the dollar sign ($).

$name = "John";
$age = 25;

✍️ Declaring Variables in PHP

✅ Syntax:

$variable_name = value;

✅ Naming Rules:

  • Must start with $
  • Must begin with a letter or underscore (_)
  • Cannot start with a number
  • Can contain letters, numbers, and underscores

❌ Invalid:

$1name = "Invalid";   // Starts with a number

📂 PHP Variable Types

PHP is a loosely typed language, meaning you don’t need to declare a variable’s data type.

🔸 String

$greeting = "Hello World";

🔸 Integer

$score = 100;

🔸 Float (Double)

$price = 99.99;

🔸 Boolean

$isValid = true;

🔸 Array

$colors = array("Red", "Green", "Blue");

🔸 Object

class Car {
    public $brand = "Toyota";
}
$car = new Car();

🔸 NULL

$data = null;

🧪 Type Juggling

PHP automatically converts variable types when needed:

$number = "10";    // string
$sum = $number + 5;  // PHP converts "10" to 10 (integer)
echo $sum; // 15

📏 Variable Scope in PHP

🔸 Local Scope

Variables declared inside a function:

function greet() {
  $message = "Hello";
}

🔸 Global Scope

Accessible outside functions:

$siteName = "My Website";

To use a global variable inside a function:

function showSite() {
  global $siteName;
  echo $siteName;
}

🔸 Static Scope

Retains value after the function ends:

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

🧰 PHP Superglobals

These are predefined global arrays accessible from anywhere in a script:

SuperglobalUse
$_GETHTTP GET variables
$_POSTHTTP POST variables
$_REQUESTGET + POST + COOKIE
$_SERVERServer environment info
$_SESSIONSession variables
$_COOKIECookie data
$_FILESUploaded files info
$_ENVEnvironment variables
$GLOBALSReferences all global variables

🧼 Best Practices for Using Variables

✅ Always initialize variables
✅ Use meaningful names ($username > $x)
✅ Follow camelCase or snake_case
✅ Avoid unnecessary global variables
✅ Comment complex variable usage
✅ Clean up large unused variables


🧪 PHP Variable Example Exercises

Example 1: String Concatenation

$firstName = "John";
$lastName = "Doe";
echo "Welcome, " . $firstName . " " . $lastName;

Example 2: Arithmetic Operations

$a = 10;
$b = 5;
$sum = $a + $b;
echo $sum; // 15

Example 3: Associative Array

$user = array("name" => "Alice", "age" => 30);
echo $user["name"]; // Alice

Example 4: Global and Static Variables

$count = 1;
function showCount() {
  global $count;
  static $localCount = 0;
  $count++;
  $localCount++;
  echo "Global: $count, Static: $localCount";
}

🧾 Summary

  • PHP variables store data that changes during script execution.
  • All variables begin with $ and follow specific naming rules.
  • PHP supports various data types and auto-converts them as needed.
  • Scope determines where a variable can be accessed.
  • Superglobals provide access to input, sessions, cookies, and more.
  • Best practices improve maintainability and debugging.

❓ FAQ on PHP Variables

🔹 Can I declare a variable without a value?

Yes. It will be initialized as NULL:

$var;

🔹 What happens if I use an undeclared variable?

PHP may throw a notice or warning depending on error reporting settings.

🔹 Is PHP case-sensitive for variables?

Yes, $name and $Name are different variables.

🔹 How to check if a variable is set?

Use isset($var).


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

🧺 PHP Variables

Or Copy Link

CONTENTS
Scroll to Top