Thuta Learning
PHP
BasicProgrammingBeginner

Variables

PHPLesson 530 min

What you'll walk away with

  • Create variables with `$`, follow the naming rules and remember that names are case-sensitive
  • Inspect a value's type with `var_dump()` and `gettype()` and explain how dynamic typing differs from strict types
  • Choose correctly between `isset()`, `empty()`, `??` and `??=` for missing, null and falsy values
  • Predict what happens when a variable is copied, referenced with `&` or used inside a function

Explain it simply

Variables in plain words

A variable is a labelled box. In PHP the label starts with `$`, for example `$name`. You do not declare the box in advance; it appears the first time you put a value in.

The unusual part is that the type belongs to the value inside the box, not to the box. After putting the number 25 into `$age` you may put a piece of text in later and the box will not complain. A PHP variable behaves like a sticky note that can be moved to a different object.

Problem → Why → Solution

The problem: a case typo does not crash, it quietly gives a wrong answer

In the code below `$age` is defined, but the next line writes `$Age`. PHP prints `Warning: Undefined variable $Age` and carries on: it treats the missing variable as `null`, and `null + 1` is 1. The output becomes 'Next year: 1' instead of 'Next year: 26'.

The answer is wrong, yet the program finishes normally, so a bug can slip into production if nobody reads the warning. A string such as `"3"` coming from a form and being used as a number can also work only by luck.

age.php
<?php
$age = 25;
echo "Next year: " . ($Age + 1), PHP_EOL;   // Warning: Undefined variable $Age
// prints "Next year: 1", not "Next year: 26"

Why PHP keeps going

In PHP 8, reading an undefined variable is only a warning, not an exception. So keep error reporting at `E_ALL`, write variable names in one consistent style and declare types on function parameters.

Core concept: a variable is a name, and the type lives in the value

A variable name starts with `$`, followed by a letter or underscore and then any mix of letters, digits and underscores. A name such as `$1st` is not allowed. Names are case-sensitive, and `$this` is reserved by PHP for its own use. The first assignment (`=`) creates the variable. Pick one naming style, either `$userName` (camelCase) or `$user_name`, and use only that across the project.

Dynamic typing means the type is stored with the value, not with the variable. The value types are `int`, `float`, `string`, `bool`, `array`, `null` and objects. `var_dump($x)` shows both the type and the value, which makes it the best debugging tool. `gettype()` reports legacy names such as `"double"` and `"boolean"`, while `get_debug_type()` (since PHP 8.0) gives the modern `float` and `bool`.

To make types strict you declare them at the boundaries rather than on the variable: function parameters, return types and class properties (since PHP 7.4). PHP has no local declaration such as `int $x = 5;`. With `declare(strict_types=1);`, passing the string `"5"` to an `int` parameter raises a TypeError, while without it PHP silently converts it to 5.

Value`isset($v)``empty($v)`
not definedfalsetrue
`null`falsetrue
`0`truetrue
`"0"`truetrue
`""` (empty string)truetrue
`[]` (empty array)truetrue
`"hello"`truefalse

`isset()` asks only 'is it defined and not null?', while `empty()` asks 'is it falsy (0, "", "0", [], null, false)?'. `??` (null coalescing) behaves like `isset`: when the left side is missing or null it uses the right side, without a warning. `??=` assigns a value only when none is set yet. Avoid `empty()` when `0` is a genuine value.

A mental model: name, value, type
  1. Name starts with $ and is case-sensitive
  2. The first assignment creates the variable
  3. The value, not the name, has a type
  4. Missing or null? ask isset or use ??

Reassigning swaps the value inside the box. To enforce types, declare them on function parameters, return types and properties.

General pattern: working with variables

php
<?php
declare(strict_types=1);

$name = value;                          // create or overwrite
$other = $name;                         // copy the value
$alias = &$name;                        // reference: two names, one value
$result = $maybeMissing ?? "default";   // fallback when unset or null

`=` puts a value into the box, and `$other = $name` copies it, so changing one later does not touch the other. `&` makes two names point at one value. `??` supplies a fallback.

Example: creating variables and changing a type

This script creates three variables and joins text with `.`. It then creates `$Name`, which differs from `$name` only in case, to show that the two are separate. Finally it replaces the int in `$age` with a string and uses `var_dump` to watch the type change.

variables.php
<?php
declare(strict_types=1);

$greeting = "Hello";
$name = "Aung Aung";
$age = 25;

echo $greeting . " " . $name . "!" . PHP_EOL;
echo "You are " . $age . " years old." . PHP_EOL;

$Name = "Someone else";      // a different variable: names are case-sensitive
echo $name . " vs " . $Name . PHP_EOL;

var_dump($age);              // int(25)
$age = "twenty-six";         // the same variable may hold another type
var_dump($age);

Code breakdown

  1. Creating variables$name = "Aung Aung";

    Each first assignment creates the variable. No prior declaration is needed: `$age = 25;` stores an int and `$name = "..."` stores a string.

  2. Joining text with a dotecho "You are " . $age . " years old." . PHP_EOL;

    The `.` operator joins text. `$age` is an int, but PHP converts it to a string when joining; strict types do not interfere here because no function parameter is involved.

  3. A second, different variable$Name = "Someone else";

    `$Name` becomes a brand-new variable distinct from `$name`, so `Aung Aung` stays untouched and the next line prints both separately.

  4. Inspecting a typevar_dump($age); // int(25)

    `var_dump()` prints the type and the value: `int(25)`. `echo` would only print `25`, hiding the type, which is why you reach for `var_dump()` when debugging.

  5. The same name, another type$age = "twenty-six"; // the same variable may hold another type

    Assigning a string to `$age` is allowed. The second `var_dump` prints `string(10) "twenty-six"`, where 10 is the length in bytes.

You should see
Hello Aung Aung!
You are 25 years old.
Aung Aung vs Someone else
int(25)
string(10) "twenty-six"

Copies, references and unset

`$b = $a` copies the value, so changing `$b` later leaves `$a` alone. Assigning an array also behaves as a copy (PHP only does the real copying when one side is modified, which keeps it fast). `&` ties two names to one value, and `unset($c)` removes only that name, not the value. Declaring a parameter with `&` lets a function change the caller's variable directly.

references.php
<?php
declare(strict_types=1);

$a = 1;
$b = $a;        // copy
$b = 2;
echo "a=$a b=$b", PHP_EOL;

$c = &$a;       // reference: same slot
$c = 99;
echo "a=$a c=$c", PHP_EOL;

unset($c);      // removes the alias only
echo "a=$a", PHP_EOL;

function addOne(int &$n): void
{
    $n++;
}
addOne($a);
echo "a=$a", PHP_EOL;

$list = [1, 2, 3];
$copy = $list;
$copy[] = 4;
echo count($list), " ", count($copy), PHP_EOL;

The output is `a=1 b=2`, `a=99 c=99`, `a=99`, `a=100` and `3 4`. Use references only when you need them, because it becomes hard to see where a value changes.

Scope inside functions

Variables inside a function live in that function's own scope. The outer `$total` is invisible there, so the good way to share it is as a parameter. `global $total` and `$GLOBALS["total"]` exist but make code hard to follow, so avoid them. `static $calls = 0;` remembers its value between calls to the function.

scope.php
<?php
declare(strict_types=1);

$total = 10;

function showTotal(): void
{
    echo isset($total) ? "sees total" : "no total here", PHP_EOL;
}

function withParam(int $total): int
{
    return $total + 1;
}

function counter(): int
{
    static $calls = 0;
    $calls++;
    return $calls;
}

showTotal();
echo withParam($total), PHP_EOL;
counter();
counter();
echo counter(), PHP_EOL;

The output is `no total here`, `11` and `3`. PHP also has variable variables such as `$$name`, which use the text stored in `$name` as a variable name. They make code hard to read, so an array is almost always the better choice.

Checking types at the boundary

strict.php
<?php
declare(strict_types=1);

function doubleIt(int $n): int
{
    return $n * 2;
}

echo doubleIt(21), PHP_EOL;

try {
    echo doubleIt("21"), PHP_EOL;
} catch (TypeError $e) {
    echo "TypeError: a string is not accepted for an int", PHP_EOL;
}

This prints `42` and then `TypeError: a string is not accepted for an int`. Without `declare(strict_types=1);` PHP would convert `"21"` to 21 and print `42` twice. In strict mode even the float `21.0` is refused by an `int` parameter.

In real projects

Variables in real projects

Values from forms and URLs always arrive as strings, so a pattern such as `$page = (int) ($_GET["page"] ?? 1);`, with a cast and `??`, appears everywhere. Config arrays commonly give fallbacks such as `$config["timeout"] ?? 30`. Framework classes use typed properties such as `private int $count = 0;`, so you can tell what a variable holds just by reading the code.

Tools catch these mistakes as well as human reviewers. A static analysis tool such as PHPStan reports an undefined variable like `$Age` before the code ever runs, and IDEs underline it in red. Meaningful, consistently styled variable names are therefore a real safety measure in a project. A name such as `$daysLeft` instead of a single letter like `$d` also helps you, six months later, when you read the code again.

Common mistakes

Common beginner mistakes

1. A case typo and an ignored warning

Defining `$age` and reading `$Age` gives `Warning: Undefined variable $Age`, and the value becomes `null`. Do not hide warnings: keep `error_reporting = E_ALL` and fix each one as soon as you see it.

2. Using `empty()` where 0 is valid

Checking an item quantity with `if (empty($qty)) { echo "missing"; }` calls both `0` and `"0"` missing. When 0 can be a real value, test with `isset($qty)`, `$qty ?? null` or `$qty === null` instead.

3. Expecting a function to change the caller's variable

Calling `function addTax(float $price): void { $price *= 1.05; }` as `addTax($p)` and expecting `$p` to change is a mistake: the parameter is a copy. Return the result and write `$p = addTax($p);`, and use `&` only when you really need to.

Mini challenge

Mini challenge: settings with defaults

Read settings from `$input = ["theme" => "dark", "pageSize" => 0, "language" => null];`. Choose `??` or `?:` where each fits and make the difference visible in the output.

  • `$theme` falls back to `"light"` and `$language` to `"en"` when the key is missing or null
  • Read `$pageSize` with `??` so the real value `0` is kept
  • Read `$perPage` with `?:` so any falsy value becomes `10`
  • Use `??=` to add `"timezone"` as `"Asia/Yangon"` only when it is not set, then `var_dump` the results of `isset()` and `array_key_exists()` for `"language"`
settings.php
<?php
declare(strict_types=1);

$input = ["theme" => "dark", "pageSize" => 0, "language" => null];

// TODO: $theme falls back to "light" only when the key is missing or null
// TODO: $language falls back to "en" in the same way
// TODO: $pageSize keeps the real value 0 (use ??)
// TODO: $perPage uses 10 whenever the value is falsy (use ?:)

// TODO: add "timezone" => "Asia/Yangon" only when it is not set yet (??=)
// TODO: print every value, then var_dump isset() and array_key_exists() for "language"

Expected: Prints `theme=dark`, `language=en`, `pageSize=0`, `perPage=10` and `timezone=Asia/Yangon`, followed by `bool(false)` and `bool(true)`.

Show hint

`$input["pageSize"] ?? 10` keeps 0, but `$input["pageSize"] ?: 10` sees 0 as falsy and gives 10. `isset()` returns false for a null value, while `array_key_exists()` returns true whenever the key exists.

Show solution
settings.php
<?php
declare(strict_types=1);

$input = ["theme" => "dark", "pageSize" => 0, "language" => null];

$theme = $input["theme"] ?? "light";
$language = $input["language"] ?? "en";
$pageSize = $input["pageSize"] ?? 10;
$perPage = $input["pageSize"] ?: 10;

echo "theme=", $theme, PHP_EOL;
echo "language=", $language, PHP_EOL;
echo "pageSize=", $pageSize, PHP_EOL;
echo "perPage=", $perPage, PHP_EOL;

$input["timezone"] ??= "Asia/Yangon";
echo "timezone=", $input["timezone"], PHP_EOL;

var_dump(isset($input["language"]), array_key_exists("language", $input));

Quick quiz 1 / 3

What does `$a = 1; $b = &$a; $b = 7; echo $a;` output?

Quick quiz 2 / 3

For `$qty = 0;`, which statement is correct?

Quick quiz 3 / 3

What does `$rate = 5; function show() { echo $rate ?? "none"; } show();` output?

What to remember

  • A variable starts with `$`, is case-sensitive and is created by its first assignment
  • The type lives in the value and `var_dump()` shows it; declare types on parameters, returns and properties for strictness
  • `isset()` asks whether it is non-null, `empty()` whether it is falsy and `??` supplies a fallback; avoid `empty()` when 0 is valid
  • `$b = $a` copies, `&` references, and variables inside a function have their own scope

PHP Language Reference — PHP Documentation Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Variables | Thuta Learning