PHP from the ground up

Variables and types

The dollar sign, the eight kinds of value PHP has, looking at a value's type instead of guessing, and converting between them on purpose.

Part 2 of 13

Beginner14 min readBack to Courses

A variable takes its type from the value

Every variable in PHP starts with $, and there is no declaration to write: assigning is declaring. $age = 36; makes an integer, $name = "Grace"; makes a string, and the variable can hold a different type tomorrow — PHP is dynamically typed, so the type travels with the value, not with the name.

The scalar types are the ones you will use hourly: int for whole numbers, float for numbers with a decimal point, string for text, bool for true and false, and null for "no value at all". Around them sit array and object, which get chapters of their own, and the callable and resource types at the edges.

Look, do not guess

When a value is not what you expected, ask the language instead of squinting at the output. gettype($x) returns the type as a word; var_dump($x) prints the type and the value together, which is the tool you reach for while debugging, because it also shows the difference between 0, "0", false and null.

var_dump is for looking, not for shipping: it prints in a debugging format. echo prints for the reader. Keeping the two apart is a habit worth forming now.

The output of var_dump is worth reading closely: it names the type, then the value, and it puts quotes around a string. int(0), string(1) "0" and bool(false) look similar in a browser but are three different answers, and the debug view is the only place that difference is visible without guessing.

What null means

null is a value in its own right, not an absence of syntax. It says “there is no value here”, which is different from 0, "" and false — each of those is a real value that a program can use. A variable assigned null exists; a variable that was never assigned does not, and reading it produces a warning.

The distinction matters when data arrives from outside. A form field that was left empty is an empty string, not null; a database column with no value may be null; a function that found nothing may return null on purpose. is_null($value) asks the question directly, and $value === null is the comparison that does not convert anything on the way.

Converting on purpose

PHP converts types on its own when a value is used in a place it does not fit — a number inside a string, a string in arithmetic. That convenience is also the source of PHP's oldest jokes, so the honest habit is to convert deliberately: (int) $text, (float) $text, (string) $number, (bool) $value.

A cast to int of a text that does not start with digits gives 0, and a cast of null gives 0 or an empty string — quietly. That is exactly why chapter five treats == with suspicion: automatic conversion is fine when you asked for it, and a trap when you did not.

Types, asked for and converted

<?php
$name = 'Grace';        // string
$age = 36;              // int
$height = 1.72;         // float
$member = true;         // bool
$note = null;           // null

echo gettype($name) . ' ' . gettype($age) . ' ' . gettype($height) . PHP_EOL;

var_dump($age, $note);  // the debugging view: type and value

// The same variable can move to another type.
$age = 'thirty-six';
echo $age . ' is now a ' . gettype($age) . PHP_EOL;

// A deliberate conversion instead of a lucky one.
$count = (int) '12 apples';
echo $count + 1, PHP_EOL;

A packing list of values

Run it and read both the echo lines and the var_dump. Then add a `float` and a `null` of your own, print their types, and cast the number 3.9 to an int — see which way it rounds.

Output
Click "Run" to execute your code

A variable that was never set has no value; using it produces a warning and the value null. The warning is not shouting — it is PHP telling you the exact line where the assumption was wrong.

The type belongs to the value

A variable is a name in the current symbol table, and the value it points at carries the type. $age = 36; puts an integer in the table under age; a later $age = "thirty-six"; replaces the value and the type together. Nothing about the name remembers the old type.

Assignment copies the value. For scalars that is literal, and for arrays PHP waits until one side changes before duplicating the storage. Objects are the exception, and the classes chapter shows why: a variable holds a handle to the object, so two names can point at the same instance. gettype() reports the type, and it calls a float double — the same type under its older name. is_float() is the question that avoids the vocabulary.

Three type mistakes are worth recognising: reading a variable before assigning it, trusting (int) "12 apples" to fail (it becomes 12 with a warning), and comparing gettype($x) to "float" when PHP answers "double". Assign first, cast deliberately, and ask with is_int() or is_float() when the exact name does not matter.

Try these next

  • Create one value of each scalar type and print gettype() for all five.
  • Cast "3.9" to int and to float; print both and explain the difference.
  • Build a total from a numeric string and a float, then cast the result to a string for display.

A parcel label

Run it and read the two var_dump lines. Then add a `$discount = null`, print `gettype($discount)`, and convert the total to a string before printing it.

Output
Click "Run" to execute your code

Check what you learned

One question at a time. A wrong answer explains itself — take another go.

Part 1 of 5

What does the $ in $name mean?