Lesson 2 of 100
Variables12 min5 checksPHP 8.5

Variables: naming, assigning and reusing values

Learn how PHP variables are named, how assignment copies values, and how to combine variables into a result you can reuse.

01 · THE IDEAREAD → TRY → LEARN

What a variable is

A variable is a named place to keep a value so you can use it again later. In PHP, a variable name starts with a dollar sign, such as $item or $total. The program never has to say "this is a string" or "this is a number". The variable simply holds whatever value you last assigned to it.

You assign with the = operator. The name goes on the left and the expression that produces the value goes on the right. The right side is evaluated first, and the result is stored.

Naming rules

A valid name begins with a letter or an underscore. After that it may contain letters, digits and underscores. So $_4site and $total2 are valid, while $4site is not, because it begins with a digit. Names with non-ASCII bytes, including UTF-8 letters, are also accepted, but plain ASCII names are easier to type and read, so prefer them when you start out.

The most important rule for beginners is that names are case-sensitive. $var and $Var are two separate variables, as the first example shows.

Example
<?php
$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var\n";
Output
Bob, Joe

Pick clear, consistent names. A name like $unitCents tells the reader far more than $x does, and a consistent style helps you avoid mistakes caused by different capitalization.

Assignment copies the value

By default PHP assigns by value. When you write $copy = $first;, the current value of $first is copied into $copy. After that the two variables are independent, so changing one does not affect the other.

Example
<?php
$first = 'Ada';
$copy = $first;
$first = 'Grace';
echo json_encode([$first, $copy], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
echo "\n";
Output
["Grace","Ada"]

The copy keeps Ada even though $first was reassigned. PHP also supports assigning by reference with &, which makes two names refer to the same value. That is a separate topic. For now, rely on ordinary assignment, which copies.

Using variables to build a result

The real benefit of variables is that you can compute a value once, store it, and use it in later steps. Strings in double quotes can include variables directly, which is called interpolation. PHP reads the name after the $ up to the first character that cannot be part of a name, such as a space.

Example
<?php
$item = 'Pen';
$quantity = 3;
$unitCents = 150;
$totalCents = $quantity * $unitCents;
$line = "$item x$quantity = $totalCents cents";
echo $line . "\n";
Output
Pen x3 = 450 cents

Notice the order of the steps. Each variable is assigned before it is used. $totalCents is computed from two earlier variables, and $line is built from three. Reading the code from top to bottom tells you how the final text was produced.

Undefined variables

PHP does not require you to declare variables first, but you should always assign a value before reading one. Reading a variable that was never assigned produces a warning, and its value is null. A typo in a name, such as $totl instead of $total, creates exactly this problem, so a warning about an undefined variable usually means a misspelled name or a missing assignment. You can also check whether a variable has been set with isset().

Worked example: planning the exercise

Suppose you need a line of text describing a cart row, for example a pen, quantity 3, priced at 150 cents each. The steps are:

  1. Multiply quantity by the unit price in cents to get $totalCents.
  2. Split that into whole dollars with intdiv($totalCents, 100).
  3. Take the leftover cents with $totalCents % 100.
  4. Combine the pieces into one string and return it.

For 3 pens at 150 cents, the total is 450 cents. That is 4 dollars and 50 cents, so the line is Pen x3 = 4.50. Each step gets its own variable, which keeps the logic easy to follow and easy to debug. One detail needs care: when the cents are below 10, they must be padded to two digits. A total of 10 cents must read 0.10, not 0.1. The function sprintf() with the format %02d does that padding.

Exercise contract

Write cartLine(string $item, int $quantity, int $unitCents): string. It returns text in the form ITEM xQUANTITY = DOLLARS.CENTS, where the amount is the total price with exactly two decimal digits. All inputs are non-negative whole numbers. Use intermediate variables for the total, the dollars and the cents. The tests check the returned string, including quantity 0 and totals below one dollar.

Recap

  • Variables start with $ and are case-sensitive.
  • Assignment evaluates the right side and stores a copy of the value.
  • Assign before you read, and reuse computed values through well-named variables.
Before you start

Getting started

You’ll practice
  • Assign values to named variables
  • Use variable values to build a result
Your task

Make cartLine() pass all 5 checks. Run your code as often as you like, then check your answer.

exercise.phpSaved in this browserPHP 8.5
CONSOLE & CHECKS● Ready

Ready when you are

Your output will appear here.
Make it work. Then make it pass.

PHP loads on your first run. Each check starts fresh. Your code stays in this browser; clearing site data removes your progress. A check or the task looks wrong? Report a problem with this exercise.