Variables are "containers" for storing information. In PHP, a variable starts with the $ sign, followed by the name of the variable.
Unlike many other languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
To write valid PHP, your variable names must follow these specific rules:
$ sign.$age and
$AGE are different).Scope refers to the part of the script where a variable can be referenced/used. PHP has three different variable scopes:
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function.
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function.
<?php
function myTest() {
$y = 5; // local scope
echo "<p>Variable y inside function is: $y</p>";
}
myTest();
// using y outside the function will generate an error
echo "<p>Variable y outside function is: $y</p>";
?>
The global keyword is used to access a global variable from within a
function. To do this, use the global keyword before the variables (inside
the function):
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
static keyword when you first declare the variable.
$userEmail instead of
$e).global keyword inside them — this trips up almost every PHP beginner at least once.
$1total and $total-price are both invalid — names must start with a letter or underscore, and can only contain letters, digits, and underscores after that.
echo 'Total: $total'; prints the literal text $total, not its value — use double quotes for interpolation.
A second example showing variables working together in a calculation, with interpolation in the output:
<?php
$price = 250;
$quantity = 3;
$total = $price * $quantity;
echo "Total: $total taka"; // Total: 750 taka
?>
Q: Why did my variable disappear inside a function?
A: It didn't disappear — functions simply can't see outer (global) variables unless you declare them with the global keyword inside the function, as shown earlier on this page.
Q: Are PHP variable names case-sensitive?
A: Yes — $Name and $name are two completely different variables.
Q: Can I use hyphens in variable names?
A: No — PHP variable names can only contain letters, digits, and underscores. Use $total_price or $totalPrice instead of a hyphen. See the PHP manual's variable rules for the full spec.