Skip to content
LumenaryAcademy
Foundations 50 min

Values, types and control flow

PHP's types, how it converts between them, why strict_types belongs at the top of every file, and the statements that make decisions and repeat work.

Code tested · 5AI-draftedAwaiting review by a computer scientist
MotivationH

A language that tries to be helpful

PHP was designed to read data from web forms, and everything that arrives from a form is text. If a visitor types 3 into a "quantity" box, your script receives the string "3", not the number 3. Early PHP decided to be helpful about this: wherever a number was needed, it would quietly turn the string into one. "3" * 2 is 6. That made the first scripts short, and it is called type juggling.

Helpfulness has a cost. When a language converts silently, a typo or a bad input does not stop the program; it becomes a strange value that travels on and causes trouble somewhere far away. For many years PHP's comparisons were the most famous example: 0 == "abc" was true. PHP 8 fixed that particular case, and modern PHP gives you tools to switch most juggling off where it matters: type declarations, declare(strict_types=1), and the strict comparison ===.

This lesson teaches PHP's types and its conversions precisely enough that you can predict what a line does, then the statements that make decisions and repeat work. Along the way you will see the habits that experienced PHP developers follow, and why.

DefinitionsH

The types

Every value in PHP has a type, but variables do not: the same variable can hold an integer now and a string later. These are the types you will use every day.

TypeExamplesNotes
int42, -7, 0x1F, 1_000_00064 bits on all common platforms; underscores are allowed for readability
float3.14, -7.5, 1e3IEEE 754 double precision, like most languages
string"hello", 'world'A sequence of bytes, not characters (more on that in the strings lesson)
booltrue, falseCase-insensitive, but write them in lower case
nullnullThe single value meaning "no value"
array[1, 2, 3], ["id" => 7]An ordered map; PHP's list, dictionary and set all in one
objectnew DateTimeImmutable()An instance of a class; its type is the class name

There are also callable (anything you can call), iterable (an array or a traversable object) and the legacy resource (an old way of representing open files and connections, now mostly replaced by objects).

Two functions tell you a value's type: var_dump($x) prints the type and value, and is the quickest debugging tool PHP has; get_debug_type($x) (PHP 8.0) returns the type's name as a string, using the same names as type declarations. In a boolean context (an if, a while, the ! operator), PHP converts any value to true or false. The values that become false are called falsy:

php
<?php

declare(strict_types=1);

$values = [42, -7.5, "42", "", "0", "0.0", true, null, [], [0], PHP_INT_MAX + 1];

foreach ($values as $v) {
    printf("%-22s %-7s %s\n", json_encode($v), get_debug_type($v), $v ? "truthy" : "falsy");
}
text
42                     int     truthy
-7.5                   float   truthy
"42"                   string  truthy
""                     string  falsy
"0"                    string  falsy
"0.0"                  string  truthy
true                   bool    truthy
null                   null    falsy
[]                     array   falsy
[0]                    array   truthy
9.223372036854776e+18  float   truthy

The falsy values are false, 0, 0.0, "", "0", [] and null; everything else is truthy. The odd one is the string "0": it is falsy because it looks like the number zero, while "0.0" is truthy. If a user types 0 into a form field, if ($input) treats it as empty. When you mean "is this string empty?", say so: if ($input === "").

The last line shows integer overflow: PHP_INT_MAX + 1 does not wrap around or raise an error; it silently becomes a float, which cannot represent every large integer exactly. For exact big numbers, PHP has the bcmath and gmp extensions (and since 8.4 the BcMath\Number class).

ExplanationH

Equal, and identical

PHP has two equality operators, and choosing between them is one of the first professional habits to build.

  • $a === $b (identical) is true when both values have the same type and the same value. No conversion happens.
  • $a == $b (equal) converts the values to a common type first, following a table of rules, and then compares.
php
<?php

declare(strict_types=1);

$pairs = [[0, "abc"], ["1", "01"], ["10", "1e1"], [100, "1e2"], [null, false], ["abc", "ABC"], [1.0, 1]];

foreach ($pairs as [$a, $b]) {
    printf(
        "%-5s vs %-6s  == %-5s  === %s\n",
        var_export($a, true),
        var_export($b, true),
        var_export($a == $b, true),
        var_export($a === $b, true),
    );
}

var_dump("5" + 3, "2.5" * 2, 7 / 2, intdiv(7, 2), -7 % 3, 2 ** 10, 0.1 + 0.2 === 0.3);

try {
    var_dump("apples" + 3);
} catch (TypeError $e) {
    echo "TypeError: ", $e->getMessage(), "\n";
}
text
0     vs 'abc'   == false  === false
'1'   vs '01'    == true   === false
'10'  vs '1e1'   == true   === false
100   vs '1e2'   == true   === false
NULL  vs false   == true   === false
'abc' vs 'ABC'   == false  === false
1.0   vs 1       == true   === false
int(8)
float(5)
float(3.5)
int(3)
int(-1)
int(1024)
bool(false)
TypeError: Unsupported operand types: string + int

Look at the second and third rows. When both sides of == are numeric strings, PHP compares them as numbers: "1" == "01" and "10" == "1e1" are true. That is surprising if the strings are product codes, phone numbers or password hashes. Real security bugs have come from comparing hashes with ==, because two different hash strings that both look like 0e… (zero times ten to some power) compare equal as numbers. The first row shows the PHP 8 change: comparing a number with a non-numeric string now compares them as strings, so 0 == "abc" is false. In PHP 7 it was true.

The habit, then: use === and !== by default, and use == only when you have thought about the conversion and want it. Linters and static analysers can enforce this.

The arithmetic lines show the other side of juggling. A numeric string used with an arithmetic operator becomes a number, so "5" + 3 is int(8). Division with / returns a float unless the result is a whole number of two integers, so 7 / 2 is 3.5; use intdiv for integer division. The remainder % takes the sign of the left operand, so -7 % 3 is -1. And 0.1 + 0.2 === 0.3 is false for the same reason as in every language with binary floats: neither 0.1 nor 0.2 is exactly representable. Never store money as a float; store whole cents (or the smallest unit of the currency) as integers, or use a decimal library.

A string that is not numeric at all, such as "apples", cannot take part in arithmetic: PHP 8 throws a TypeError. A string that merely starts with a number, such as "5 apples", is still converted, but with a warning (A non-numeric value encountered). Treat that warning as a bug.

DefinitionsH

What strict_types really does

PHP lets you declare the types of a function's parameters and its return value. The question is what happens when a caller passes the wrong type.

Definition— Coercive mode (the default)

If a scalar argument has the wrong type but can be converted sensibly, PHP converts it. A function declared function label(int $count) called as label("3") receives the integer 3. If the conversion is impossible (label("3 apples")), PHP throws a TypeError.

Definition— Strict mode

With declare(strict_types=1); as the first statement of a file, scalar arguments in calls made from that file must already have the declared type, or PHP throws a TypeError. The one exception is widening: an int is accepted where a float is declared. Return values of functions defined in the file are checked strictly too.

php
<?php

declare(strict_types=1);

function area(float $width, float $height): float
{
    return $width * $height;
}

function label(int $count): string
{
    return $count === 1 ? "1 item" : "$count items";
}

echo area(3, 4.5), "\n";   // an int is accepted where a float is expected
echo label(3), "\n";

try {
    echo label("3"), "\n";
} catch (TypeError $e) {
    echo "TypeError: ", explode(", called", $e->getMessage())[0], "\n";
}
text
13.5
3 items
TypeError: label(): Argument #1 ($count) must be of type int, string given

Without the declare line, the same calls behave like this (we ran it; the comments show what printed):

php
label("3");        // "3 items": the string is converted
label(true);       // "1 item": true becomes 1
label(3.5);        // "3 items", plus "Deprecated: Implicit conversion from float 3.5 to int loses precision"
label("3 apples"); // TypeError: not a well-formed number

Three facts about strict mode surprise people, so learn them now:

  1. It is per file, and it applies to the calls written in that file. A strict file calling a function defined in a non-strict file is checked strictly; a non-strict file calling a function from a strict file is not.
  2. It changes only function and method calls (and returns). Operators still juggle: "5" + 3 is 8 even in strict mode, as the comparison program showed.
  3. It is a compile-time declaration, so it must be the very first statement, before any other code.

Modern PHP projects put declare(strict_types=1); at the top of every file. Your form inputs are still strings, of course; the difference is that you convert them on purpose, once, at the edge of your program, and everything inside works with real integers and floats.

Worked examplesH

Converting on purpose

If strict mode stops PHP from converting for you, you need to convert yourself. There are three common tools, and they disagree in instructive ways:

  • A cast, such as (int) $s, (float) $s, (string) $n or (bool) $x, always succeeds. It takes whatever it can and silently drops the rest.
  • is_numeric($s) answers a yes-or-no question: does this string look like a number of any kind (integer, decimal, exponent, with surrounding whitespace)?
  • filter_var($s, FILTER_VALIDATE_INT) returns the integer if the whole string is a well-formed integer, and false otherwise. It can also check a range, with options such as ["options" => ["min_range" => 1]].
php
<?php

declare(strict_types=1);

foreach (["42", " 42 ", "42abc", "4.2", "", "abc", "1e3"] as $input) {
    printf(
        "%-8s (int) %-5d  is_numeric %-5s  filter_var %s\n",
        json_encode($input),
        (int) $input,
        var_export(is_numeric($input), true),
        var_export(filter_var($input, FILTER_VALIDATE_INT), true),
    );
}
text
"42"     (int) 42     is_numeric true   filter_var 42
" 42 "   (int) 42     is_numeric true   filter_var 42
"42abc"  (int) 42     is_numeric false  filter_var false
"4.2"    (int) 4      is_numeric true   filter_var false
""       (int) 0      is_numeric false  filter_var false
"abc"    (int) 0      is_numeric false  filter_var false
"1e3"    (int) 1000   is_numeric true   filter_var false

Read the cast column carefully: "42abc" became 42, "abc" and the empty string became 0, and "4.2" lost its fraction, all without a word of complaint. A cast is the right tool when you already know the value is valid (a database column declared as an integer, say). For anything a person typed, validate first: filter_var refuses the doubtful cases, and you can show the user a helpful message instead of saving a 0 nobody meant. Note that filter_var trims surrounding whitespace before checking, which is usually what you want for form fields.

A last habit: compare filter_var's result with === false, never with !, because a perfectly valid input of "0" returns the integer 0, which is falsy.

Worked examplesH

Making decisions and repeating work

if, elseif, else work as in C and Java: parentheses around the condition, braces around the body. PHP spells elseif as one word (else if also works).

php
if ($stock === 0) {
    echo "Sold out";
} elseif ($stock < 5) {
    echo "Only $stock left";
} else {
    echo "In stock";
}

Small operators that replace whole if statements are everywhere in PHP code:

php
$label = $isMember ? "member" : "guest";     // ternary
$page = $_GET["page"] ?? 1;                   // null coalescing: left side unless it is null or missing
$settings["timeout"] ??= 30;                  // assign only if null or missing
$city = $user?->address?->city;               // nullsafe (8.0): null if any step is null
$order = $a <=> $b;                           // spaceship: -1, 0 or 1, for sorting

?? is special: it does not warn when the key or variable does not exist, which makes it the standard way to read optional input. Note that it tests for null, not falsiness, so 0 ?? 5 is 0, while 0 ?: 5 is 5.

match (PHP 8.0) is an expression that compares a value against arms and returns the result of the first that matches. It compares with ===, it has no fall-through, and if no arm matches it throws an UnhandledMatchError instead of carrying on silently. match (true) is a common idiom for a chain of conditions:

php
<?php

declare(strict_types=1);

function describe(int $celsius): string
{
    return match (true) {
        $celsius < 0 => "freezing",
        $celsius < 15 => "cool",
        $celsius < 25 => "mild",
        $celsius < 35 => "hot",
        default => "dangerously hot",
    };
}

function dayKind(int $isoDay): string
{
    return match ($isoDay) {
        1, 2, 3, 4, 5 => "weekday",
        6, 7 => "weekend",
    };
}

foreach ([-4, 12, 24, 31, 41] as $t) {
    printf("%4d °C  %s\n", $t, describe($t));
}

echo dayKind(6), "\n";
try {
    echo dayKind(9), "\n";
} catch (\UnhandledMatchError $e) {
    echo get_class($e), ": ", $e->getMessage(), "\n";
}

// How many steps does the Collatz rule take to bring 27 down to 1?
$n = 27;
$steps = 0;
$peak = $n;
while ($n !== 1) {
    $n = $n % 2 === 0 ? intdiv($n, 2) : 3 * $n + 1;
    $peak = max($peak, $n);
    $steps++;
}
echo "27 reaches 1 after $steps steps, peaking at $peak\n";
text
  -4 °C  freezing
  12 °C  cool
  24 °C  mild
  31 °C  hot
  41 °C  dangerously hot
weekend
UnhandledMatchError: Unhandled match case 9
27 reaches 1 after 111 steps, peaking at 9232

PHP also has the older switch statement. It compares with loose == and falls through from one case to the next unless you write break. Both behaviours cause bugs, so in new code prefer match whenever you are choosing a value; keep switch for the rare case where you really want several statements per branch and fall-through.

Loops. while and do … while repeat while a condition holds; the Collatz loop above is a while. for has the familiar three parts:

php
for ($i = 10; $i > 0; $i -= 3) {
    echo $i, " ";      // 10 7 4 1
}

But most loops in PHP are foreach, which walks an array (or any iterable object) element by element, optionally with keys:

php
foreach ($prices as $item => $price) {
    if ($price === 0) {
        continue;          // skip to the next element
    }
    if ($item === "STOP") {
        break;             // leave the loop
    }
    echo "$item costs $price\n";
}

break 2 and continue 2 act on the enclosing loop two levels out, which is occasionally useful in nested loops and usually a sign that the inner loop should become a function.

Common misconceptionsH

Common misunderstandings

Misconception

"strict_types makes PHP a statically typed language." It does not. Types are still checked when the code runs, at each call, and only where you have declared them. A function without declarations accepts anything. Static checking, before the program runs, comes from tools such as PHPStan and Psalm, which you will meet in the last lesson.

Misconception

"if ($value) checks whether a value was given." It checks whether the value is truthy. The number 0, the string "0" and an empty array all fail it. Ask the question you mean: !== null, === "", isset(...), count(...) === 0.

Misconception

"switch and match are the same thing with different syntax." switch compares loosely and falls through; match compares strictly, never falls through, returns a value, and throws if nothing matches. A switch on "0" with a case 0: will run that case; a match will not.

Misconception

"?? and ?: do the same thing." $a ?? $b returns $a unless it is null or undefined. $a ?: $b returns $a unless it is falsy, so it replaces 0, "" and "0" too, and it warns if $a is undefined. Use ?? for defaults of missing input.

Exercises

Exercises

1. Values, types and control flow

Warm-upComputational

How many of these eight values are falsy in PHP?

$values = [0, "0", "0.0", " ", [], [[]], null, "false"];

2. Values, types and control flow

CoreComputational

Which of these comparisons are true in PHP 8? List the letters.

  • a: 0 == "abc"
  • b: "1" == "01"
  • c: null == false
  • d: "abc" == "ABC"
  • e: "10" == "1e1"
  • f: 100 === 100.0

Write elements separated by commas. Order and repeats don’t matter — just like in a set!

3. Values, types and control flow

CoreComputational

What does this line print?

echo intdiv(17, 5), " ", 17 % 5, " ", 17 / 5 > 3 ? "yes" : "no", "\n";

4. Values, types and control flow

CoreComputational

What does this program print?

<?php
$code = "2";
echo match ($code) {
    2 => "two (int)",
    "2" => "two (string)",
    default => "other",
}, "\n";

5. Values, types and control flow

CoreComputational

What does this program print?

<?php
$qty = 0;
echo $qty ?: 1, $qty ?? 1, "\n";

6. Values, types and control flow

CoreComputational

What number does this program print?

<?php
$n = 0;
for ($i = 1; $i <= 20; $i++) {
    if ($i % 3 === 0) {
        continue;
    }
    if ($i > 10) {
        break;
    }
    $n += $i;
}
echo $n, "\n";

7. Values, types and control flow

StretchHuman

File lib.php has no declare(strict_types=1) and defines function label(int $count): string. File app.php starts with declare(strict_types=1);, includes lib.php, and calls label("3"). What happens?

Choose one

Further reading and resources