Variables

PHP · Lesson 4 of 50 7 min read Updated

A program needs somewhere to keep the information it is working with: a student's name, a cart total, the number of wickets that have fallen. In PHP, you keep that information in variables.

In this lesson you will learn how to create variables, the rules for naming them, how to see what is inside them, and how to deal with variables that do not exist yet.

Creating a variable

A variable is a named box that holds a value. In PHP every variable name starts with a dollar sign $. You create a variable simply by giving it a value with the = sign:

PHP
<?php
declare(strict_types=1);

$studentName = 'Priya';
$age = 19;
$feePaid = true;

echo "Name: " . $studentName . "\n";
echo "Age: $age\n";
Output
Name: Priya
Age: 19

There is no special keyword to declare a variable, and you do not say what type of data it will hold. PHP works out the type from the value. This is called dynamic typing.

Read = as "store" or "becomes", not "equals". The line $age = 19; means "store 19 in the box called $age". Checking whether two values are equal uses different operators, which you will learn in Operators.

The example shows two ways to put a variable into text. The dot . joins pieces of text together, and inside double quotes PHP replaces $age with its value. Strings covers both in detail.

Naming rules

Variable names follow a few strict rules:

  • A name starts with $, followed by a letter or an underscore.
  • After that you can use letters, digits and underscores.
  • No spaces, hyphens or other symbols.
  • Names are case-sensitive: $total and $Total are different variables.
NameValid?Why
$cityYesLetters only
$_countYesStarts with an underscore
$marks2026YesDigits after the first letter
$2ndPlaceNoStarts with a digit
$first-nameNoHyphen is not allowed
$first nameNoSpace is not allowed

Choose names that explain the value: $monthlyRent is much clearer than $mr or $x. This course uses camelCase ($monthlyRent), where each new word starts with a capital letter. Some projects use snake_case ($monthly_rent). Pick one style and stay with it.

Do not name a variable $this. It has a special meaning inside classes, which you will meet in Classes & Objects.

Changing values and inspecting them

A variable can be given a new value at any time. It can even switch to a different type of value. To see exactly what a variable holds, use var_dump(). It prints the type and the value, which makes it the best tool for checking your work while you learn.

PHP
<?php
declare(strict_types=1);

$score = 45;
var_dump($score);

$score = $score + 6;
var_dump($score);

$score = 'retired hurt';
var_dump($score);
Output
int(45)
int(51)
string(12) "retired hurt"

The line $score = $score + 6; reads the old value (45), adds 6 and stores the result back. For strings, var_dump() also shows the length in bytes, here 12.

Being able to change a variable's type is flexible, but it can also cause bugs. A good habit is to keep one kind of value in each variable for its whole life.

Assigning copies the value

When you assign one variable to another, PHP copies the value. Changing the copy does not change the original. This is true for numbers and strings, and in PHP it is also true for arrays.

PHP
<?php
declare(strict_types=1);

$priceInJaipur = 1299;
$priceInPune = $priceInJaipur;
$priceInPune = 1399;

echo "Jaipur: ₹$priceInJaipur, Pune: ₹$priceInPune\n";

$teamA = ['Rohan', 'Kabir'];
$teamB = $teamA;
$teamB[] = 'Farhan';

echo count($teamA), " players in team A\n";
echo count($teamB), " players in team B\n";
Output
Jaipur: ₹1299, Pune: ₹1399
2 players in team A
3 players in team B

$teamB[] = 'Farhan'; adds a name to the end of the array $teamB only. If you know JavaScript, note that this is different: in JavaScript, both names would point to the same array. Objects in PHP work more like JavaScript, as you will see in later lessons. You will learn arrays properly in Arrays.

Variables that do not exist

If you read a variable that was never created, PHP shows a warning and uses the special value null, which means "no value":

Text
Warning: Undefined variable $pinCode in shop.php on line 6

This usually means a typing mistake in the name, so read these warnings carefully. To check safely whether a variable exists, use these tools:

  • isset($x) gives true if $x exists and is not null.
  • $x ?? 'default' gives the value of $x, or the default if $x does not exist or is null. It never shows a warning.
  • unset($x) deletes a variable.
PHP
<?php
declare(strict_types=1);

$city = 'Kochi';
var_dump(isset($city));
var_dump(isset($pinCode));

$pinCode = null;
var_dump(isset($pinCode));

echo $nickname ?? 'No nickname', "\n";

unset($city);
var_dump(isset($city));
Output
bool(true)
bool(false)
bool(false)
No nickname
bool(false)

Notice the third line: $pinCode exists, but it holds null, so isset() still says false. You will use isset() and ?? all the time when reading form data, where a field may or may not have been sent.

Variables inside functions

Variables you create at the top of a file are not visible inside functions. A function has its own separate set of variables, which keeps functions independent and easy to test. If a function needs a value, pass it in as a parameter. You will see how in Functions.

You may see the global keyword in older code, used to reach outside variables from inside a function. Avoid it: it makes code hard to follow and hard to test.

Common mistakes

  • Forgetting the $. Writing total = 5; is a parse error. Every variable needs $.
  • Typos in names. $studentName and $studentname are different. An "Undefined variable" warning usually means a typo.
  • Reading a variable before setting it. Give variables a starting value, or use ?? when a value may be missing.
  • Expecting echo to show true or false. echo true; prints 1 and echo false; prints nothing. Use var_dump() to see booleans.

Key points

  • Variable names start with $, then a letter or underscore, and are case-sensitive.
  • = stores a value; PHP decides the type from the value.
  • var_dump() shows a variable's type and value, which is ideal for debugging.
  • Assigning one variable to another copies the value, including arrays.
  • Reading an undefined variable gives a warning and the value null.
  • Use isset(), ?? and unset() to check, default and remove variables.

Exercise

Write a script for a shop bill. Store an item name ('School bag'), a price (899) and a quantity (2) in three variables. Work out the total in a fourth variable and print a line such as "2 x School bag = ₹1798". Then change the quantity to 3, recalculate the total and print the line again. Finally, print a discount code using ?? with a variable $couponCode that you never create, so that it shows "No coupon".

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

$item = 'School bag';
$price = 899;
$quantity = 2;
$total = $price * $quantity;
echo "$quantity x $item = ₹$total\n";

$quantity = 3;
$total = $price * $quantity;
echo "$quantity x $item = ₹$total\n";

echo $couponCode ?? 'No coupon', "\n";
Output
2 x School bag = ₹1798
3 x School bag = ₹2697
No coupon

The total must be recalculated after the quantity changes, because $total stores a value, not a formula. The ?? operator supplies "No coupon" without a warning.

Quick Quiz

1. Which variable name is valid in PHP?

2. What does isset($x) return when $x holds null?

3. After $a = [1, 2]; $b = $a; $b[] = 3;, how many items does $a have?

4. What happens when you echo a variable that was never created?

Learn PHP with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call