Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 147 ยท Data Types

Booleans and null

Learn PHP booleans and null - true and false, the complete truthy and falsy table, the "0" string trap, null and unset variables, ?? and nullable types.

A boolean (bool) has exactly two possible values: true and false. Every if statement, every loop condition and every comparison works with booleans, so they're the hinge that all decision-making in your code turns on. null is PHP's way of saying "no value at all": a variable that was never given a value, a function that returned nothing, a database column left empty.

The two belong in the same lesson because they meet constantly. PHP will treat any value as a boolean when you put it in a condition, and null is one of the values that counts as false. The rules that decide what counts as true or false are short, but a couple of them (the string "0" is false, the string "0.0" is true) surprise even experienced developers. This lesson gives you the complete table, then shows how to work with null safely, including a first look at the ?? operator and nullable types.

You'll use the comparisons that produce booleans in Comparison Operators and combine them in Logical Operators.

true and false

Write booleans with the constants true and false. They're case-insensitive (TRUE and False work), but lowercase is the standard style. Most booleans in real code don't come from literals but from comparisons and functions whose names start with is_, has_ or can_:

PHP Where booleans come from

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

var_dump() shows bool(true) or bool(false) for each value. Naming boolean variables as yes/no questions ($isAdult, $hasAt, $canEdit) makes conditions read like English.

Printing a boolean

echo converts true to the string "1" and false to an empty string, so a false value prints nothing at all:

PHP Echoing booleans is misleading

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is Found: [] and Saved: [1], which is easy to misread. To show a boolean to a human, convert it yourself with the ternary operator ($found ? 'yes' : 'no', covered in Null Coalescing, Ternary and Nullsafe Operators). To inspect one while debugging, use var_dump() or var_export(), which print false instead of nothing.

In arithmetic, true counts as 1 and false as 0: true + true is int(2). That occasionally helps (counting how many conditions are true) but usually signals a bug.

Truthy and falsy values

When PHP needs a boolean and gets something else, such as if ($name) or while ($line), it converts the value to bool. Values that become false are called falsy; everything else is truthy. The falsy list is short enough to memorize:

Value Type As a boolean
false bool false
0, -0 int false
0.0, -0.0 float false
'' (empty string) string false
'0' (the string zero) string false
[] (empty array) array false
null null false

Everything else is truthy, including some values that look false:

Value As a boolean Why it's surprising
'0.0' true Only the exact string '0' is falsy
'false' true It's a non-empty string
' ' (a space) true Non-empty
[0], [null], [''] true The array isn't empty, whatever it contains
-1 true Any non-zero number is true
Any object true Even an object with no properties
PHP Testing the truthy and falsy table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The array keys are just labels for printing (note that PHP turns the keys '0' and '-1' into integers, which doesn't matter here). The loop prints each value next to its verdict: the first seven are falsy, the last six truthy. Add your own entries to check any case you're unsure about.

The special float NAN is truthy too, but PHP 8.5 adds a warning when it's converted to a boolean (unexpected NAN value was coerced to bool), because a NAN in a condition almost always means an earlier calculation went wrong.

The "0" trap

The rule that '0' is falsy exists so that numeric form input like "0" behaves like the number 0. It becomes a bug when a string can legitimately be "0":

PHP When a valid value looks false

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The function treats '0' exactly like an empty field. If zero is a valid answer, test what you actually mean: $input === '' for "empty", or trim($input) === '' to also reject spaces.

The second half shows the most famous version of this bug. strpos() returns the position where it found the text, or false if it didn't. Here 'php' is at position 0, which is falsy, so the plain truthiness check says "Not found". Always compare strpos() results with !== false, or use str_contains() (PHP 8.0+) when you only need yes or no. Many built-in functions return false on failure but a falsy-looking value like 0 or '' on success, so this habit pays off everywhere.

null: the absence of a value

null is a type with a single value, also written null (case-insensitive, lowercase by convention). A variable is null when:

  • you assigned null to it,
  • it was destroyed with unset(),
  • it's a function's return value and the function didn't return anything,
  • you read a variable that was never defined (with a warning).
PHP Where null comes from

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last line is a mistake on purpose: reading an undefined variable gives Warning: Undefined variable $neverDefined in main.php on line 18 and then NULL. PHP keeps running, but the warning tells you something is misspelled or missing. Note that var_dump() prints the null type as NULL in capitals, and gettype(null) returns "NULL" too, while the modern get_debug_type(null) returns "null".

To test for null, use $x === null or is_null($x). Both are exact. Avoid $x == null: the loose comparison is also true for false, 0, '' and [] (but, oddly, not for '0'). It's confusing enough that you should simply not use it. Comparison Operators explains the full == rules.

null in expressions

null quietly converts in most expressions: it becomes 0 in arithmetic (null + 5 is 5), '' in strings (null . 'x' is 'x') and false in conditions. Passing null to a built-in function that expects a string, like strlen(null), has been deprecated since PHP 8.1; PHP is gradually making unexpected nulls visible instead of silently converting them.

isset, empty and null

Two language constructs check variables without warnings, even when the variable doesn't exist:

  • isset($x) is true if $x exists and is not null.
  • empty($x) is true if $x doesn't exist or is falsy. It's the same as !isset($x) || !$x.
$x is isset($x) empty($x) $x === null
not defined false true true (with a warning)
null false true true
0 or '0' true true false
'' true true false
'hello' true false false
[] true true false

isset() is the right tool for "was this provided?", for example isset($_GET['page']). Be careful with empty(): because it inherits the '0' trap, empty($_POST['quantity']) rejects a legitimate zero. Both constructs are covered again with arrays in Associative Arrays.

Default values with ?? and ??=

Because "use this value, or a default if it's missing" is so common, PHP has an operator for it. The null coalescing operator ?? returns its left side if it exists and isn't null, and otherwise its right side. Like isset(), it never warns about missing variables or array keys. ??= (PHP 7.4+) assigns a default only when the variable is null or missing:

PHP Defaults with the null coalescing operator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that $pageSize stays 0: ?? only replaces null and missing values, so a real zero survives. Compare the last line, which uses the short ternary ?:. That operator replaces any falsy value, so it turns the zero into 20. Choose ?? when zero, '' or false are valid values. Both operators get a full lesson in Null Coalescing, Ternary and Nullsafe Operators.

A preview: nullable types

When you declare a function's parameter or return type, you can say that null is allowed by putting a ? in front of the type. ?string means "a string or null":

PHP
function findUserName(int $id): ?string
{
    $users = [1 => 'Ada', 2 => 'Linus'];

    return $users[$id] ?? null;
}

$name = findUserName(3);          // null: no such user
echo $name ?? 'Unknown user';     // Unknown user

Returning null for "not found" is a common, honest design: the ?string in the signature warns every caller that they must handle the missing case. PHP also has bool, true and false as types for parameters and return values (true as a standalone type since PHP 8.2). You'll learn the whole system in Type Declarations.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these values is truthy?

    Only the exact string '0' is a falsy string (along with ''). '0.0' is a non-empty string other than '0', so it's truthy.
  2. 2. What does echo 'Done: ' . false; print?

    false converts to an empty string, so nothing appears after the label. Use var_dump or a ternary to show booleans.
  3. 3. $pos = strpos('hello', 'h'); Why is if ($pos) a bug?

    strpos returns the position (here 0) or false if not found. Compare with !== false, or use str_contains when you only need a yes/no answer.
  4. 4. $data = ['count' => 0]; What is $data['count'] ?? 10?

    The ?? operator replaces only null or missing values. The key exists and holds 0, so 0 is returned. The short ternary ?: would have returned 10.
  5. 5. $x = null; Which expression is true?

    isset returns false for null, empty returns true for null (so !empty is false), and null is not identical to false. is_null and === null are the exact tests.

Summary

  • bool has two values, true and false. echo prints them as "1" and "", so use var_dump() or a ternary to display them.
  • The falsy values are false, 0, 0.0, '', '0', [] and null. Everything else is truthy, including '0.0', 'false', ' ' and [0].
  • Functions that return a position or false (like strpos()) must be checked with !== false.
  • null means "no value". It comes from assignments, unset(), functions without return and undefined variables (with a warning). Test it with === null or is_null().
  • isset() means "exists and isn't null"; empty() means "missing or falsy" and has the '0' trap.
  • $value ?? $default and $x ??= $default replace only null or missing values; ?: replaces any falsy value.
  • A ? before a type (?string) allows null in parameters and return values.

Next: Type Juggling and Casting