PHP Variables

Declaring Variables

All variables in PHP start with a $ symbol followed by the variable name:

$name = "Alice";
$age = 25;
$price = 9.99;

Naming Rules

  • Start with a letter or underscore
  • Cannot start with a number
  • Can contain letters, numbers, and underscores
  • Are case-sensitive
$UserName ≠ $username

Variable Scope

PHP has three main scopes:

  • Local: Inside a function
  • Global: Outside any function
  • Static: Preserves a local variable’s value between calls
Loading...
Output:
Loading...
Output:

Variable Variables

You can use one variable to name another (dynamic variable):

$name = "PHP";
$$name = "Rocks";

echo $PHP;  // Outputs: Rocks

Use cautiously — this can make code harder to read.

Variable Reassignment

You can freely reassign variables to different types:

$x = 5;
$x = "now a string";

This is allowed because PHP is dynamically typed.

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic