blog / guides

PHP variables explained: a practical beginner guide

by Luke published 8 min read

the short answer

A PHP variable is a named box for a value, and its name always starts with a dollar sign. $name = "Sam"; puts Sam in a box called $name. You never say what type a variable holds: PHP works it out from the value, and the same variable can hold a number now and text later. Names are case-sensitive, so $name and $Name are two different variables.

A PHP variable is a named box that holds a value. Its name always starts with a dollar sign, and you make it simply by putting something in it:

try it · php
<?php
$name = "Sam";
$age = 9;
$height = 1.32;
echo $name . "\n";
echo $age . "\n";
echo $height . "\n";
Sam
9
1.32

echo shows a value, the dot joins two pieces of text together, and "\n" starts a new line. Every PHP example here begins with <?php, which marks where the PHP code starts.

Notice what is missing: you never say what kind of value each box holds. PHP works that out by itself. This guide covers the types a variable can hold, putting variables inside text, changing them, constants, naming rules, and the mistakes that trip up beginners. Every example runs right here in your browser.

Making a variable

$age = 9; has four parts:

  • $age is the name, dollar sign included.
  • = means put this value in the box. Read it as “becomes”, not “equals”.
  • 9 is the value.
  • ; ends the instruction.

There is no separate step to create the variable. The first time you assign a value, the box exists.

The types a variable can hold

Every value in PHP has a type. The ones you will use first:

  • string: text, in quotes, like "Sam".
  • int: a whole number, like 9 or -40.
  • float: a number with a decimal point, like 1.32.
  • bool: true or false.
  • null: a box with nothing in it.

var_dump shows both the type and the value, which makes it the best tool for checking what a variable really holds:

try it · php
<?php
$name = "Sam";
$age = 9;
$height = 1.32;
$likesCats = true;
$nickname = null;
var_dump($name, $age, $height, $likesCats, $nickname);
string(3) "Sam"
int(9)
float(1.32)
bool(true)
NULL

The 3 in string(3) is the length of the text. Arrays, which hold a whole list of values, get a lesson of their own once these basics are comfortable.

Why echo is not enough for true and false

echo shows true as 1, and false as nothing at all. Here the brackets show that false printed an empty space:

try it · php
<?php
$likesCats = false;
echo "[", $likesCats, "]";
[]

When a value looks wrong, reach for var_dump instead of echo.

Putting variables inside text

Inside double quotes, PHP swaps each variable for its value. Inside single quotes, it does not:

try it · php
<?php
$name = "Sam";
$age = 9;
echo "$name is $age\n";
echo '$name is $age\n';
echo "\n";
echo $name . " is " . $age . "\n";
echo "{$name}'s cat\n";
Sam is 9
$name is $age\n
Sam is 9
Sam's cat

Single quotes also ignore \n, which is why the second line shows it as plain characters. The dot builds the same sentence piece by piece. Curly brackets, as in {$name}, mark exactly where a variable’s name ends, which helps when letters follow straight after it.

Changing a variable

Give a variable a new value and the old one is gone. In PHP, the new value does not even need to be the same type:

try it · php
<?php
$score = 10;
$score = $score + 5;
$score += 1;
echo $score . "\n";
$score = "sixteen";
echo $score . "\n";
echo gettype($score) . "\n";
16
sixteen
string

$score += 1 is short for $score = $score + 1. gettype tells you the type a variable holds right now. Being able to switch types is handy, but a box that holds a number one moment and text the next is easy to get wrong, so most code keeps each variable to one type.

Numbers and maths

Dividing two whole numbers gives the full answer, even when it is not a whole number:

try it · php
<?php
echo 7 / 2 . "\n";
echo intdiv(7, 2) . "\n";
echo 7 % 2 . "\n";
3.5
3
1

intdiv keeps only the whole part, and % gives the remainder.

A float can hide a tiny error

Floats store most decimals as a very close approximation. echo rounds that away, but var_dump and comparisons do not:

try it · php
<?php
echo 0.1 + 0.2 . "\n";
var_dump(0.1 + 0.2);
var_dump(0.1 + 0.2 == 0.3);
0.3
float(0.30000000000000004)
bool(false)

For money, store whole pence as an int, then divide by 100 only when you show the price.

Text that looks like a number

PHP turns text into a number when it can, so + and . give very different answers:

try it · php
<?php
echo "5" + 3 . "\n";
echo "5" . 3 . "\n";
8
53

+ always does maths, and . always joins text. Text that is not a number at all cannot be added:

try it · php
<?php
echo "abc" + 1;
TypeError: Unsupported operand types: string + int (line 2)

Checking a variable with isset

isset asks whether a variable exists and holds something other than null:

try it · php
<?php
$nickname = null;
var_dump(isset($nickname));
var_dump(isset($name));
$name = "Sam";
var_dump(isset($name));
bool(false)
bool(false)
bool(true)

It is the safe way to check for a value that might not be there, such as something typed into a form.

Constants: values that never change

A constant is made with const or define(). Constants have no dollar sign and are usually written in capitals:

try it · php
<?php
const MAX_LIVES = 3;
define("SHOP_NAME", "Pip's Pets");
echo MAX_LIVES . "\n";
echo SHOP_NAME . "\n";
3
Pip's Pets

Try to change one and PHP will not even read the file:

try it · php
<?php
const MAX_LIVES = 3;
MAX_LIVES = 4;
ParseError: syntax error, unexpected token "=" (line 3)

Naming variables

The rules:

  • After the $, a name starts with a letter or an underscore, never a digit.
  • The rest can be letters, digits and underscores, with no spaces.
  • Capitals matter: $name and $Name are two separate boxes.

PHP code uses both $playerName and $player_name styles. Pick one for a project and stick to it, and choose names that say what the value is.

Common mistakes

Forgetting the dollar sign

try it · php
<?php
name = "Sam";
ParseError: syntax error, unexpected token "=" (line 2)

Without the $, PHP does not see a variable, so the = makes no sense to it.

Spelling a name two ways

try it · php
<?php
$playerName = "Sam";
echo $playername;
ErrorException: Undefined variable $playername (line 3)

Gwecode’s run boxes stop at this, so you notice it straight away. A standard PHP setup only prints a warning and carries on as if the variable held null, which can hide the bug.

Single quotes when you wanted the value

echo 'Hello, $name'; prints the dollar sign and the name, not Sam. Use double quotes whenever a variable should be swapped in.

Using + to join text

"Sam" + " Smith" is maths, not joining, and PHP 8 stops with a TypeError. Join text with a dot: "Sam" . " Smith".

Starting a name with a digit

try it · php
<?php
$2ndPlace = "Ava";
ParseError: syntax error, unexpected integer "2", expecting variable or "{" or "$" (line 2)

Put the number later instead, as in $secondPlace or $place2.

A short exercise

A cinema ticket costs £7.50. Make variables for the film’s name, the number of tickets and the price of one ticket in pence. Work out the total and print this line:

2 tickets for Robot Picnic cost £15.00

To try it out, open the playground from the button at the bottom of the page and choose PHP. number_format($pence / 100, 2) turns pence into pounds with two decimal places.

One possible answer

try it · php
<?php
$film = "Robot Picnic";
$tickets = 2;
$ticketPrice = 750;
$total = $tickets * $ticketPrice;
echo "$tickets tickets for $film cost £" . number_format($total / 100, 2);
2 tickets for Robot Picnic cost £15.00

The price stays a whole number of pence until the very end, so no float rounding can creep in.

Your next step

Variables are where every PHP program starts. Gwecode’s PHP Level 1 begins with exactly this idea, a variable as a labelled box, then moves on to text, maths, decisions, loops, arrays and functions of your own, one short lesson at a time. Its level check has you build a sports day score board. Every lesson is free and runs in your browser. Create a free account to keep your progress, and start with the lesson below.

practise this · php · lessonA variable is a labelled boxstart the lesson

questions

Why do PHP variables start with a dollar sign?

The $ tells PHP that a word is a variable, not a function or a keyword. It also lets PHP spot variables inside double-quoted text, which is how "Hello, $name" works.

Do I need to declare a variable before using it in PHP?

No. A variable is made the first time you put a value in it. Reading one before that gives an Undefined variable warning, so always give it a value first.

What is the difference between single and double quotes in PHP?

Double quotes swap variables for their values and understand codes like \n for a new line. Single quotes keep the text exactly as typed, dollar signs included.

Are PHP variable names case-sensitive?

Yes. $score and $Score are different variables. Function names and keywords are not case-sensitive, which is why the rule for variables can catch people out.

How do I make a value that cannot change?

Use a constant, made with const or define(). Constants have no dollar sign and are usually written in capitals, like MAX_LIVES. Trying to change one later is an error.

keep going.