PHP Variables
Variables are containers for storing data and always start with a dollar sign.
Syntax
$variableName = value;A variable in PHP starts with the $ sign, followed by the name of the variable.
Naming rules
- A variable name must start with a letter or underscore.
- It can only contain letters, numbers and underscores.
- Names are case-sensitive.
PHP has no command to declare a variable — it is created the moment you first assign a value to it.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Storing user input from a form ($_POST) before you validate or save it.
- Holding an intermediate result, like a running total accumulated inside a loop.
- Reading a config value once and reusing it across the rest of a script.
More examples
Declare once, reuse later
Variables begin with $ and can be combined in later expressions.
<?php
$price = 20;
$qty = 3;
$total = $price * $qty;
echo "Total: $" . $total;Loosely typed — the type follows the value
PHP infers the type from the assigned value, and it may change at runtime.
<?php
$data = 42; // int
$data = "hello"; // now a string
echo $data;Variable variables
$$name uses the value of $name ('score') as the variable's name.
<?php
$name = "score";
$$name = 100;
echo $score; // 100
Discussion