Variables

In PHP, variables are containers for data — like boxes that hold information your script can use later. A variable in PHP starts with a $ sign, followed by its name:

$x = 5;
$y = "John";

You don’t need to “declare” variables in PHP — they come to life as soon as you assign them a value.

When assigning text, use quotes:

$name = "Luma";

Naming Rules

  • Must start with $
  • Must begin with a letter or underscore
  • Can contain letters, numbers, and underscores
  • Can’t start with a number
  • Are case-sensitive ($age$AGE)

Outputting Variables

Use echo to display text or variable values:

$txt = "W3Schools.com";
echo "I love $txt!";      // I love W3Schools.com!
echo "I love " . $txt . "!"; // Same thing using concatenation

You can also combine numbers:

$x = 5;
$y = 4;
echo $x + $y; // 9

PHP doesn’t require you to define types — it decides automatically:

$x = 5;       // integer
$y = "John";  // string

That’s why PHP is called loosely typed: types are flexible, and conversions often happen automatically.

Checking Data Types

Use var_dump() to inspect a variable’s type and value:

var_dump(5);
var_dump("John");
var_dump(3.14);
var_dump(true);
var_dump([2, 3, 56]);
var_dump(NULL);
I am doing the exercises. It seems when we use a global variable inside a function and change its value, if you try to output it outside the function, it will inherit the value set inside the function. Is that right? For example, here.

You can assign the same value to multiple variables in one go:

$x = $y = $z = "Fruit";

Variable Scope

A variable’s scope determines where it can be used in your script. There are three scopes in PHP:

  • local
  • global
  • static

Global vs Local

Variables declared outside functions are global and can only be used outside functions:

$x = 5;

function myTest() {
  echo $x; // error – not visible here
}

Variables declared inside functions are local:

function myTest() {
  $x = 5;
  echo $x; // works
}

Each function keeps its own local variables — even if they share the same name.

Now, to use global variables inside a function, you must declare them with the ‘global‘ keyword:

$x = 5;
$y = 10;

function myTest() {
  global $x, $y;
  $y = $x + $y;
}

myTest();
echo $y; // 15

Alternatively, use the $GLOBALS[index] array, which fetches the values of global variables by setting the index to the name of the variable:

function myTest() {
  $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}

Static Variables

Normally, local variables are deleted when a function ends. But if you need a variable to remember its value between calls, use static:

function myTest() {
  static $x = 0;
  echo $x;
  $x++;
}

myTest(); // 0
myTest(); // 1
myTest(); // 2

The variable $x stays local but keeps its value across executions.