Variables
A variable is a name that holds a value. You can read the value, change it and use it anywhere in the program. In PHP a variable name always starts with the $ sign.
Declaration
A variable is created the first time you assign to it. The = sign means "put this value into the variable":
<?php
$name = 'Anna';
$age = 25;
echo $name; // AnnaThere is no need to declare a variable in advance or to state its type.
Changing the value
You can assign a new value to a variable — the old one is lost. The variable itself may appear on the right-hand side of =:
<?php
$count = 1;
$count = $count + 1;
echo $count; // 2The expression on the right (1 + 1) is evaluated first, then the result is stored in $count.
Naming rules
- a name starts with a letter or an underscore:
$user,$_cache; - after that you can use letters, digits and underscores;
- names are case-sensitive:
$ageand$Ageare different variables.
Pick names that say what the variable holds: $userName is better than $x. When a name consists of several words, each following word starts with a capital letter — this style is called camelCase.
String interpolation
Inside double-quoted strings variables are substituted automatically; inside single quotes they are not:
<?php
$name = 'Anna';
echo "Hello, $name!\n"; // Hello, Anna!
echo 'Hello, $name!'; // Hello, $name!If letters follow the variable directly, wrap the name in curly braces — otherwise PHP treats those letters as part of the name:
<?php
$item = 'file';
echo "Found 3 {$item}s"; // Found 3 filesUndefined variables
If you read a variable that was never assigned, PHP prints an Undefined variable warning and uses an empty value. The usual cause is a typo in the name, so these warnings are worth paying attention to.