← Back to PHP Course | Chapter 1: Introduction & Basics | Lesson 10 of 13

PHP Variables

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
<?php
$name = "Alice";
echo $name;
?>

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
<?php
$value = "Hello";
var_dump($value);
$value = 42;
var_dump($value);
?>

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
<?php
$name = "Alice";
echo "Double-quoted: $name\n";
echo 'Single-quoted: $name';
?>

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
<?php
$globalVar = "I am global";

function showScope() {
    $localVar = "I am local";
    echo $localVar . "\n";
}
showScope();
echo $globalVar;
?>

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
<?php
$name = "color";
$$name = "blue";
echo $color;
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.