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.
$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var\n";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.
$first = 'Ada';
$copy = $first;
$first = 'Grace';
echo json_encode([$first, $copy], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
echo "\n";["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.
$item = 'Pen';
$quantity = 3;
$unitCents = 150;
$totalCents = $quantity * $unitCents;
$line = "$item x$quantity = $totalCents cents";
echo $line . "\n";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:
- Multiply quantity by the unit price in cents to get
$totalCents. - Split that into whole dollars with
intdiv($totalCents, 100). - Take the leftover cents with
$totalCents % 100. - 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.
Getting started
- Assign values to named variables
- Use variable values to build a result