PHP Variables
A variable is a name that holds a value. In PHP every variable starts with $.
Assigning
PHP
<?php $name = 'Ada'; $age = 36; $active = true; $ratio = 0.382; $friends = ['Grace', 'Linus', 'Margaret'];
PHP is dynamically typed
Variables don't have a fixed type — the value does. Reassigning is fine:
PHP
$x = 1; // int $x = 'hello'; // now a string $x = [1, 2, 3]; // now an array
Naming rules
- Start with
$, then a letter or underscore. After that letters, digits, underscores. - Case-sensitive —
$userand$Userare different. - Convention:
camelCasefor variables,PascalCasefor classes,UPPER_SNAKEfor constants.
Reference vs value
PHP
$a = 10; $b = $a; // copy of value $b = 99; echo $a; // 10 — unaffected $a = [1, 2, 3]; $c = &$a; // c is a reference to a $c[] = 4; print_r($a); // [1, 2, 3, 4]
Type hints (PHP 7+)
Functions and properties can declare types so PHP enforces them:
PHP
class User {
public string $name;
public int $age;
}
Tip: Use
var_dump($x) when you're not sure what's in a variable. It prints the type and value — invaluable for debugging.Example
Example
<?php $name = 'Ada'; $age = 36; $active = true; echo "$name is $age and active=$active";Try it Yourself »
Exercise
Every PHP variable starts with this character.
name = 'Ada';
A single character — dollar sign.
Discussion
Loading…