PHP Variables
In this page:
Variable Declaration
Every PHP variable name starts with a dollar sign — $name, not name — which is how the interpreter tells a variable apart from a constant, function, or keyword at a glance. You never declare a type up front; the variable simply starts existing the first time you assign it a value.
Example: Variable Declaration
<?php
$name = "Alice";
echo $name;
?>
Login to try C/C++/Java/PHP code in the editor
Dynamic Typing
Because PHP is dynamically typed, the same variable can hold a string at one point in your script and a number later on — PHP just reassigns it and moves on. This flexibility is convenient for quick scripts, but it's also why type-related bugs can creep in silently in larger codebases.
Example: Dynamic Typing
<?php
$value = "Hello";
var_dump($value);
$value = 42;
var_dump($value);
?>
Login to try C/C++/Java/PHP code in the editor
Outputting Variables
Double-quoted strings actively substitute a variable's current value wherever $variable appears inside them — this is called interpolation. Single-quoted strings skip that step entirely and print the literal characters $variable, which is faster when you genuinely don't need substitution.
Example: Outputting Variables
<?php
$name = "Alice";
echo "Double-quoted: $name\n";
echo 'Single-quoted: $name';
?>
Login to try C/C++/Java/PHP code in the editor
Variable Scope
A variable declared outside any function has global scope and is visible to top-level code throughout the script. A variable declared inside a function is local to that function by default — it's created fresh on each call and disappears once the function returns, invisible to code outside it.
Example: Variable Scope
<?php
$globalVar = "I am global";
function showScope() {
$localVar = "I am local";
echo $localVar . "\n";
}
showScope();
echo $globalVar;
?>
Login to try C/C++/Java/PHP code in the editor
Variable Variables
PHP supports 'variable variables' using a double dollar sign: $$name uses the *value* of $name as the name of another variable. It's a rare, advanced feature — genuinely useful in a handful of dynamic scenarios, but easy to overuse in ways that make code hard to trace.
Example: Variable Variables
<?php
$name = "color";
$$name = "blue";
echo $color;
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: