Skip to content

PHP 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"];

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 ($name and $Name are 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 allowed

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;

Scope determines where a variable can be accessed.

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 $GLOBALS
function showSiteNameAlt() {
echo $GLOBALS['siteName'];
}

Variables declared inside a function only exist within that function:

function greet() {
$greeting = "Hello";
echo $greeting; // Works
}
greet();
// echo $greeting; // Error: undefined variable

Static variables retain their value between function calls:

function counter() {
static $count = 0;
$count++;
echo "Count: $count\n";
}
counter(); // Count: 1
counter(); // Count: 2
counter(); // Count: 3

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 info

By default, assigning one variable to another copies the value. Using & creates a reference where both variables point to the same data.

$original = "Hello";
$reference = &$original;
$reference = "World";
echo $original; // "World" (both point to same data)

Functions can modify the original variable when you pass by reference:

function double(&$value) {
$value = $value * 2;
}
$number = 10;
double($number);
echo $number; // 20
$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]

Always initialize variables before using them:

$total = 0;
$items = [];
$user = null;

The ?? operator provides a default when a variable is null or undefined:

$username = $_GET['user'] ?? 'guest';
$config = $customConfig ?? $defaultConfig ?? [];