Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 147 ยท Getting Started

Variables

Learn how PHP variables work - naming rules, assignment and copying, dynamic typing, isset, unset and empty, undefined variable warnings, references and variable variables.

A variable is a named container for a value. You store a price, a user's name or a list of products under a name, and later use the name to read or change the value. Variables are how a program remembers things while it runs.

PHP variables are easy to start with: no declaration keyword, no type to state in advance, just a $ and a name. That simplicity hides a few details worth learning early: what happens when you copy a variable, how to check whether one exists, and what PHP does when you read a variable you never set. This lesson covers all of them.

Creating and using variables

Every variable name starts with a dollar sign $. You create a variable by assigning a value to it with =, the assignment operator. There's no separate declaration step:

PHP Creating variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Read $total = $price * $quantity; from right to left: PHP first calculates $price * $quantity, then stores the result in $total. The = sign means "store", not "is equal to" (comparison uses == and ===, covered in Comparison Operators).

A variable can be reassigned at any time, and the new value replaces the old one:

PHP Changing a variable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

+=, -=, *=, .= and friends are compound assignment operators; ++ and -- add or subtract one. Arithmetic and Assignment Operators covers them all.

Naming rules

A variable name, after the $:

  • must start with a letter or an underscore ($name, $_temp),
  • may continue with letters, digits and underscores ($line2, $max_size),
  • can't start with a digit: $1st is a parse error,
  • is case-sensitive: $total, $Total and $TOTAL are three different variables.

PHP technically allows non-ASCII letters too ($cafรฉ works), but stick to plain English letters so that every developer can type your names.

$this is reserved: inside a class it refers to the current object, and assigning to it is a fatal error. You'll use it in Object-Oriented Programming in PHP.

Naming conventions

PHP doesn't enforce a style, but the community does. Modern PHP code (including the PSR/PER coding standards) uses camelCase for variables: start lowercase, capitalize each following word.

PHP
<?php

$firstName = 'Ada';        // camelCase: the modern convention
$orderTotal = 99.5;
$isLoggedIn = false;       // booleans read well with is/has/can
$maxRetries = 3;

$first_name = 'Ada';       // snake_case: common in older code and WordPress

More important than the style is choosing names that say what the value means. $daysUntilExpiry tells the next reader everything; $d or $temp2 tells them nothing.

Dynamic typing

PHP is dynamically typed: a variable doesn't have a fixed type. The value has a type, and the same variable can hold an integer now and a string later. get_debug_type() (PHP 8.0) tells you the type of the current value:

PHP One variable, many types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This prints int, string, float, array and null. Flexibility is convenient, but a variable that silently changes type is also a common source of bugs. Good practice is to keep each variable to one type, and to use type declarations on functions and properties so PHP checks types for you. You'll get the full tour of types in Data Types and of type checks in Type Declarations.

Assignment copies values

When you assign one variable to another, PHP copies the value. Changing one afterwards doesn't affect the other:

PHP Assignment makes a copy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Even arrays are copied: $prices keeps its original first element. (PHP is smart about this and only really copies the array at the moment you change one of them, a technique called copy-on-write, so assigning large arrays is cheap.)

Objects behave differently. A variable holds a handle to an object, so assigning it gives you a second handle to the same object. That difference is explained in Classes, Properties and Methods.

A preview of references

If you really want two names for the same value, use a reference with =&:

PHP A reference: two names, one value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

References are mainly used to let a function change a variable you pass in, or to modify array elements in a foreach loop. They can also cause surprising bugs, so use them sparingly. You'll meet them again in Parameters and Arguments and foreach Loops.

Undefined variables

Reading a variable that was never assigned is a mistake, and PHP 8 tells you so with a warning. The script keeps running, and the missing variable is treated as null. Run this example, which triggers the warning on purpose:

PHP Reading an undefined variable (warning on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP prints:

TEXT
Warning: Undefined variable $itemCout in main.php on line 5
Total: 1

The typo made $itemCout a brand-new, undefined variable, which counted as null, and null + 1 is 1. The script continued with a wrong answer. That's why you should never ignore warnings: they're often the first sign of a real bug. Keep error reporting on while developing (this editor shows everything). Errors, Warnings and Notices explains the error levels.

Old code alert: before PHP 8, reading an undefined variable was only a "notice", easy to overlook. Some legacy code relies on undefined variables silently being null. In modern PHP, always assign a variable before you read it.

isset, unset and empty

Three language constructs help you check and manage variables.

isset: does it exist and is it not null?

isset($var) returns true if the variable exists and its value is not null. It never triggers a warning, so it's the safe way to check something that might be missing, such as an optional form field. It accepts several variables and returns true only if all are set.

unset: remove a variable

unset($var) destroys a variable. Afterwards, it's as if it was never assigned. unset() also removes elements from arrays: unset($cart['apple']);.

empty: is it missing or "falsy"?

empty($var) returns true if the variable doesn't exist or its value counts as false: false, 0, 0.0, '', '0', null or an empty array []. Like isset(), it never warns.

PHP isset, unset and empty

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The results are: true, false, false, false, true, true, false, then no email given.

Two lessons hide in there. First, isset() treats a variable holding null the same as a missing one. Second, empty() is broader than it looks: an age of 0 or a quantity of '0' is "empty". When 0 is a valid value, compare explicitly instead (for example $age === null or $quantity === '').

The last line uses the null coalescing operator ??: $email ?? 'default' gives $email if it's set and not null, otherwise the default, without any warning. It's the modern, concise way to supply defaults; Null Coalescing, Ternary and Nullsafe Operators covers it in detail.

Value of $x isset($x) empty($x) $x ?? 'default'
never assigned false true 'default'
null false true 'default'
0 or '0' true true 0 or '0'
'' true true ''
'hello' true false 'hello'

Variable variables (and why to avoid them)

PHP lets you use the value of one variable as the name of another, with a double dollar sign. This is called a variable variable:

PHP Variable variables (avoid in real code)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

It works, but it's almost always a bad idea. Code that creates variables from data is hard to read, impossible for IDEs and static analyzers to check, and dangerous if the name comes from user input (a visitor could overwrite any variable in your script). Whenever you're tempted to use $$name, use an array with keys instead, as the second half of the example does. You'll learn arrays in Arrays and Associative Arrays.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? $a = 5; $b = $a; $b = 9; echo $a;

    Assignment copies the value. Changing $b afterwards doesn't affect $a.
  2. 2. Which variable name is invalid in PHP?

    A variable name can't start with a digit. $2total is a parse error.
  3. 3. What does var_dump(isset($x)); print after $x = null;?

    isset() returns false when the variable is null, exactly as if it didn't exist.
  4. 4. $qty = '0'; Which expression is true?

    The string '0' is one of the values empty() treats as empty. It is set, and ?? returns '0' because it isn't null.
  5. 5. What happens when a script reads $prise but only $price was assigned?

    PHP 8 shows Warning: Undefined variable $prise and continues with null, which usually leads to wrong results.

Summary

  • Variables start with $, are created by assignment with =, and can be reassigned at any time.
  • Names start with a letter or underscore, contain letters, digits and underscores, and are case-sensitive. Use descriptive camelCase names.
  • PHP is dynamically typed: values have types, variables don't. Use get_debug_type() to see a value's type.
  • Assignment copies values, including arrays; =& creates a reference (two names, one value).
  • Reading an undefined variable gives a warning and null. Treat warnings as bugs.
  • isset() checks "exists and not null", unset() removes a variable, empty() also counts 0, '0', '' and [] as empty. ?? supplies defaults safely.
  • Avoid variable variables ($$name); use arrays with keys instead.

Next: Constants, where you'll store values that never change and meet PHP's built-in and magic constants.