Skip to content

PHP Variables

PHP variables are created the moment you assign a value to them. Unlike some languages, you don’t need to explicitly declare variables before use.

  • They start with the $ symbol followed by the variable name.
// Variables are created the moment you assign a value
$message = "Hello, World!";
$count = 42;
$price = 19.99;
$isActive = true;
$items = array("apple", "banana", "orange");
  • The dollar sign distinguishes variables from other programming elements like function names or keywords. Without it, PHP wouldn’t know whether you’re referring to stored data or trying to use a command.
  • The dollar sign serves as a signal flag that says “container ahead!”
  • It’s PHP’s way of immediately telling you “this is a variable” when you read the code.

  • Must start with $ followed by a letter or underscore
  • Can contain letters, numbers, and underscores
  • Case-sensitive ($name and $Name are different)
  • Cannot start with a number
// Valid variable names
$userName = "john";
$user_name = "john";
$_userName = "john";
$userName123 = "john";
// Invalid variable names
// $123user = "john"; // Cannot start with number
// $user-name = "john"; // Hyphens not allowed
// $user name = "john"; // Spaces not allowed

<?php
// Good variable names tell a story
$customer_email = "alice@email.com"; // Anyone reading this knows exactly what data this contains
$monthly_salary = 5000; // Clear time period and purpose
$is_logged_in = true; // Boolean variables often start with "is_" to show true/false nature
// Poor variable names create confusion
$x = "alice@email.com"; // What does 'x' mean? You'll forget in a week
$data = 5000; // What kind of data? Too vague to be helpful
$flag = true; // What is this flag for? Unclear purpose
?>

<?php
// These work perfectly - PHP accepts them
$user_name = "John"; // Letters and underscores - excellent choice
$totalPrice = 99.99; // CamelCase - also perfectly valid
$_temporary = "temp data"; // Starting underscore - allowed for special cases
$item2 = "second item"; // Numbers after letters - completely fine
// These will break your program - PHP rejects them
$2users = "invalid"; // Cannot start with a number - think about it: how would PHP distinguish this from the number 2 followed by "users"?
$user-name = "broken"; // Hyphens confused with minus signs - PHP thinks you're trying to subtract
$for = "problem"; // "for" is a reserved word - PHP needs it for loops
?>

Variables declared outside functions have global scope:

$globalVar = "I'm global";
function testGlobal() {
global $globalVar; // Access global variable
echo $globalVar;
}
// Alternative using $GLOBALS
function testGlobals() {
echo $GLOBALS['globalVar'];
}

Variables declared inside functions are local:

function testLocal() {
$localVar = "I'm local";
echo $localVar; // Works fine
}
testLocal();
// echo $localVar; // Error: Undefined variable

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 variables available everywhere:

// $_GET, $_POST, $_SESSION, $_COOKIE, $_SERVER, $_ENV, $_FILES
echo $_SERVER['HTTP_HOST']; // Current domain
echo $_GET['param']; // URL parameter
echo $_POST['field']; // Form field
// $GLOBALS contains all global variables
$GLOBALS['customVar'] = "Available everywhere";

$original = "Hello";
$reference = &$original; // $reference points to $original
$reference = "World";
echo $original; // Outputs: "World"
// Both variables point to the same memory location
unset($reference);
echo $original; // Still outputs: "World"
function modifyValue(&$value) {
$value = $value * 2;
}
$number = 10;
modifyValue($number);
echo $number; // Outputs: 20
$array = [1, 2, 3, 4, 5];
// Modify array elements by reference
foreach ($array as &$value) {
$value *= 2;
}
unset($value); // Always unset reference after foreach
print_r($array); // [2, 4, 6, 8, 10]

// Use descriptive names
$userName = "john_doe"; // Good
$u = "john_doe"; // Bad
// Use camelCase or snake_case consistently
$firstName = "John"; // camelCase
$first_name = "John"; // snake_case
// Boolean variables should be descriptive
$isActive = true; // Good
$active = true; // Less clear
// Constants in UPPER_CASE
const MAX_RETRY_ATTEMPTS = 3;
// Use strict types (PHP 7+)
declare(strict_types=1);
function addNumbers(int $a, int $b): int {
return $a + $b;
}
// Input validation
function processAge($age) {
if (!is_numeric($age) || $age < 0 || $age > 150) {
throw new InvalidArgumentException('Invalid age provided');
}
return (int)$age;
}
// Initialize variables before use
$total = 0;
$items = [];
$user = null;
// Use null coalescing operator (PHP 7+)
$username = $_GET['user'] ?? 'guest';
$config = $userConfig ?? $defaultConfig ?? [];
// Null coalescing assignment (PHP 7.4+)
$cache ??= expensive_operation();
// Unset large variables when done
$largeArray = range(1, 1000000);
// ... process array
unset($largeArray);
// Use references for large data structures
function processLargeArray(array &$data) {
// Process without copying the array
foreach ($data as &$item) {
$item = strtoupper($item);
}
}