PHP Variable Basics

Variables in PHP are fundamental containers for storing data. A PHP variable name starts with a dollar sign ($), followed by a letter or underscore, and can contain letters, numbers, or underscores. Variable names are case-sensitive.

Syntax

Here are the rules for valid PHP variable names −

// Valid variables
$var = 10;
$VAR = "Hello";     // Different from $var (case-sensitive)
$marks_1 = 67;
$_val = 0;

// Invalid variables
var = 10;           // Missing $ sign
$4sqr = 16;         // Cannot start with number
$my name = "Hello"; // Spaces not allowed
$my$name = "Hello"; // $ only allowed at start

Variable Assignment by Reference

Variables can be assigned by reference using the ampersand (&) operator. When assigned by reference, both variables point to the same memory location −

<?php
$var1 = "Hello";
$var2 = &$var1;     // Assignment by reference
echo $var1 . " " . $var2 . "<br>";

$var2 = "Hi there"; // Changing $var2 affects $var1
echo $var1 . " " . $var2 . "<br>";
?>
Hello Hello
Hi there Hi there

Uninitialized Variables

PHP assigns default values to uninitialized variables based on context. Integers and floats default to 0, booleans to FALSE, and strings to empty. Modern PHP versions issue notices for undefined variables −

<?php
$var1 = 10;
$var2 = $var1 + $var2; // $var2 is uninitialized
echo $var1 . " " . $var2 . "<br>";

$x = "Hello";
unset($x);
var_dump($x); // Variable no longer exists
?>
10 10
NULL
PHP Notice: Undefined variable: var2
PHP Notice: Undefined variable: x

Cumulative Operations with Uninitialized Variables

Uninitialized variables in mathematical operations are treated as 0 −

<?php
$sum = $sum + 10; // $sum starts as 0
var_dump($sum);
?>
int(10)
PHP Notice: Undefined variable: sum

Object Property Assignment

PHP can create a default object when assigning properties to undefined variables, though this generates a warning −

<?php
$obj->name = "XYZ"; // Creates stdClass object
var_dump($obj);
?>
object(stdClass)#1 (1) {
  ["name"]=>
  string(3) "XYZ"
}
PHP Warning: Creating default object from empty value

Conclusion

PHP variables must follow specific naming conventions and are case-sensitive. While PHP allows uninitialized variables with default values, it's best practice to initialize variables explicitly to avoid notices and ensure code clarity.

Updated on: 2026-03-15T09:20:17+05:30

410 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements