All lessons

Variables

6 min · PHP

Store values in named boxes called variables.

PHP · Variables0/5 cleared

Enemy 1 of 5

What a variable actually is

A variable is a named container that holds a value so you can refer to it later without retyping it. Think of it like a labeled box: you put something inside, and from then on you can just say the label instead of describing the contents every time.

In PHP, every variable name starts with a dollar sign ($) — this is one of the language's most recognizable quirks, and it's different from most other popular languages, which use no sigil at all (Python, Ruby, Java) or a keyword like let/var (JavaScript, Dart). The $ isn't optional and it isn't part of the name conceptually, but you do have to type it every single time you reference the variable, both when creating it and when using it later.

To create a variable, write $name = value;. This is called an assignment: the = sign takes the value on the right and stores it in the variable on the left. Unlike some strictly-typed languages, PHP doesn't require you to declare a type up front — the variable just becomes whatever type the value is, and it can change later if you assign something new to it.

A very common beginner slip-up is forgetting the $ on one occurrence but not another — PHP will treat $name and name as two completely unrelated things (name without the $ would actually be interpreted as a constant, and using an undefined one raises a warning). Consistency with the $ is what makes your variable actually work.

You
Cold-Start Frostling

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: Ada