PHP Variables
What are Variables?
Section titled “What are Variables?”Variables store data that can be used throughout your script. In PHP, variables start with the $ symbol followed by the variable name. You don’t need to declare a type; PHP figures it out from the value you assign.
$message = "Hello, World!";$count = 42;$price = 19.99;$isActive = true;$items = ["apple", "banana", "orange"];Naming Rules
Section titled “Naming Rules”PHP enforces these rules for variable names:
- Must start with
$followed by a letter or underscore - Can contain letters, numbers, and underscores
- Cannot start with a number
- Case-sensitive (
$nameand$Nameare different variables)
// Valid names$userName = "john";$user_name = "john";$_temporary = "temp";$item2 = "second";
// Invalid names// $2users = "invalid"; // Cannot start with number// $user-name = "broken"; // Hyphens not allowed// $user name = "broken"; // Spaces not allowedDescriptive Names
Section titled “Descriptive Names”Good variable names make your code easier to understand:
// Clear and descriptive$customer_email = "alice@email.com";$monthly_salary = 5000;$is_logged_in = true;
// Vague and confusing$x = "alice@email.com";$data = 5000;$flag = true;Variable Scope
Section titled “Variable Scope”Scope determines where a variable can be accessed.
Global Scope
Section titled “Global Scope”Variables declared outside functions are global. To access them inside a function, use the global keyword or $GLOBALS array:
$siteName = "My Website";
function showSiteName() { global $siteName; echo $siteName;}
// Alternative using $GLOBALSfunction showSiteNameAlt() { echo $GLOBALS['siteName'];}Local Scope
Section titled “Local Scope”Variables declared inside a function only exist within that function:
function greet() { $greeting = "Hello"; echo $greeting; // Works}
greet();// echo $greeting; // Error: undefined variableStatic Variables
Section titled “Static Variables”Static variables retain their value between function calls:
function counter() { static $count = 0; $count++; echo "Count: $count\n";}
counter(); // Count: 1counter(); // Count: 2counter(); // Count: 3Superglobals
Section titled “Superglobals”Built-in arrays available everywhere in your script:
$_GET['id']; // URL parameters (?id=123)$_POST['email']; // Form data (POST method)$_SESSION['user']; // Session data$_COOKIE['token']; // Cookie values$_SERVER['HTTP_HOST']; // Server/request infoVariable References
Section titled “Variable References”By default, assigning one variable to another copies the value. Using & creates a reference where both variables point to the same data.
Reference Assignment
Section titled “Reference Assignment”$original = "Hello";$reference = &$original;
$reference = "World";echo $original; // "World" (both point to same data)Passing by Reference
Section titled “Passing by Reference”Functions can modify the original variable when you pass by reference:
function double(&$value) { $value = $value * 2;}
$number = 10;double($number);echo $number; // 20References in Loops
Section titled “References in Loops”$prices = [10, 20, 30];
foreach ($prices as &$price) { $price *= 1.1; // Add 10% to each}unset($price); // Always unset after reference loop
print_r($prices); // [11, 22, 33]Best Practices
Section titled “Best Practices”Initialize Variables
Section titled “Initialize Variables”Always initialize variables before using them:
$total = 0;$items = [];$user = null;Use Null Coalescing
Section titled “Use Null Coalescing”The ?? operator provides a default when a variable is null or undefined:
$username = $_GET['user'] ?? 'guest';$config = $customConfig ?? $defaultConfig ?? [];