Assertions
suggest changeAn assertion is a check that states something you believe is always true at a given point in the program. If the belief turns out to be wrong, the program has a bug, and the assertion stops it right where the bug shows up instead of letting bad data travel further.
PHP has a built-in assert() language construct for this. Its key property is that assertions can be switched off completely in production, so they cost nothing there, while in development and in tests they catch mistakes early.
Assertions are not a replacement for validating input or for exceptions. They are for conditions that can only be false if your code is wrong. Errors that can happen in correct code (bad user input, missing files, network failures) should throw exceptions, see Exception and Error handling and Custom errors.
A first assertion
assert() takes an expression. If it evaluates to true, nothing happens. If it's false, PHP throws an AssertionError:
<?php
function average(array $numbers): float
{
assert(count($numbers) > 0);
return array_sum($numbers) / count($numbers);
}
echo average([2, 4, 9]), "\n";
echo average([]), "\n";
Output (with the development setting zend.assertions=1):
5
Fatal error: Uncaught AssertionError: assert(count($numbers) > 0) in ...\a1.php:4
Stack trace:
#0 ...\a1.php(4): assert(false, 'assert(count($n...')
#1 ...\a1.php(9): average(Array)
#2 {main}
thrown in ...\a1.php on line 4
When you don't give a message, PHP uses the source code of the asserted expression as the message. The stack trace shows which caller passed the empty array, which is usually exactly what you need to find the bug.
AssertionError is an Error, not an Exception
AssertionError extends Error. It's in the same family as TypeError and ValueError, which are thrown when the code itself is wrong:
<?php
function average(array $numbers): float
{
assert(count($numbers) > 0);
return array_sum($numbers) / count($numbers);
}
try {
average([]);
} catch (AssertionError $e) {
echo get_class($e), ": ", $e->getMessage(), "\n";
var_dump($e instanceof Error);
var_dump($e instanceof Exception);
}
Output:
AssertionError: assert(count($numbers) > 0)
bool(true)
bool(false)
This matters because a lot of application code has catch (Exception $e) blocks. They do not catch a failed assertion, which is intentional: a bug shouldn't be silently swallowed by code that handles ordinary runtime failures.
<?php
function process(array $order): void
{
assert(isset($order['id']), 'order without id');
echo "processing order {$order['id']}\n";
}
try {
process([]);
} catch (Exception $e) {
echo "caught by catch (Exception)\n";
} catch (Throwable $e) {
echo "caught by catch (Throwable): ", get_class($e), "\n";
}
Output:
caught by catch (Throwable): AssertionError
You'd normally only catch AssertionError in a top-level error handler (to log it) or in tests. Catching it to carry on as if nothing happened defeats the purpose.
Custom messages
The auto-generated message is the expression's source code. PHP prints it from the parsed code, so the formatting is normalized:
<?php
$items = ['a' => 1, 'b' => 2];
$checks = [
fn() => assert(isset($items['c'])),
fn() => assert(in_array(3, $items, true)),
fn() => assert($items['a']+$items['b']===4),
fn() => assert(array_is_list($items) && count($items) > 0),
];
foreach ($checks as $check) {
try {
$check();
} catch (AssertionError $e) {
echo $e->getMessage(), "\n";
}
}
Output:
assert(isset($items['c']))
assert(in_array(3, $items, true))
assert($items['a'] + $items['b'] === 4)
assert(array_is_list($items) && count($items) > 0)
That tells you what failed but not the values involved. Pass a string as the second argument to explain the problem:
<?php
function setDiscount(float $percent): float
{
assert($percent >= 0 && $percent <= 100, "discount must be 0..100, got $percent");
return $percent / 100;
}
try {
setDiscount(150);
} catch (AssertionError $e) {
echo $e->getMessage(), "\n";
}
Output:
discount must be 0..100, got 150
The message is an argument of assert(), so it's only built when assertions are active. String interpolation in the message costs nothing in production.
Throwing your own exception
Instead of a string, the second argument can be any Throwable. PHP throws that object instead of AssertionError:
<?php
class InvariantViolation extends LogicException {}
$stock = -3;
try {
assert($stock >= 0, new InvariantViolation("stock went negative: $stock"));
} catch (InvariantViolation $e) {
echo get_class($e), ": ", $e->getMessage(), "\n";
}
Output:
InvariantViolation: stock went negative: -3
Keep in mind that this is still an assertion: with assertions disabled, the check doesn't run and nothing is thrown. If the check must always run, use a plain if and throw.
Turning assertions on and off: zend.assertions
Assertions are controlled by the zend.assertions ini setting. It has three values:
| Value | Meaning | Typical use |
|---|---|---|
1 |
assertions are compiled and executed | development, tests, CI |
0 |
assertions are compiled but skipped at run time | rarely used |
-1 |
assertions are not compiled at all (zero cost) | production |
PHP's own php.ini-development sets zend.assertions = 1 and php.ini-production sets zend.assertions = -1. The built-in default, if no php.ini is loaded, is 1.
When assertions are off, the whole assert() call is skipped, including its arguments. Any function called inside the expression doesn't run:
<?php
function logCall(): bool
{
echo "logCall() ran\n";
return true;
}
echo "zend.assertions = ", ini_get('zend.assertions'), "\n";
assert(logCall());
assert(false, "this fails only when assertions are on");
echo "done\n";
Running it with each setting from the PHP CLI:
$ php -d zend.assertions=1 a3.php
zend.assertions = 1
logCall() ran
Fatal error: Uncaught AssertionError: this fails only when assertions are on in ...\a3.php:10
...
$ php -d zend.assertions=0 a3.php
zend.assertions = 0
done
$ php -d zend.assertions=-1 a3.php
zend.assertions = -1
done
To see the setting in effect, run php -i | grep zend.assertions (or look for it in phpinfo() output). Web servers and the CLI often use different php.ini files, so check both.
Switching at run time
You can switch between 1 and 0 with ini_set() at run time. Switching from or to -1 is only possible in php.ini (or with -d on the command line), because at -1 the assertions were never compiled into the code:
<?php
function check(): void
{
try {
assert(false, 'boom');
echo "assert skipped\n";
} catch (AssertionError $e) {
echo "assert failed: ", $e->getMessage(), "\n";
}
}
check();
ini_set('zend.assertions', '0');
check();
ini_set('zend.assertions', '1');
check();
Output with zend.assertions=1:
assert failed: boom
assert skipped
assert failed: boom
Output with zend.assertions=-1:
assert skipped
Warning: zend.assertions may be completely enabled or disabled only in php.ini in ...\c3.php on line 13
assert skipped
Warning: zend.assertions may be completely enabled or disabled only in php.ini in ...\c3.php on line 15
assert skipped
Checking whether assertions are enabled
ini_get('zend.assertions') gives you the setting. A neat trick uses an assignment inside assert(), which only happens when assertions actually run:
<?php
function assertionsEnabled(): bool
{
$enabled = false;
assert($enabled = true);
return $enabled;
}
echo "zend.assertions: ", ini_get('zend.assertions'), "\n";
var_dump(assertionsEnabled());
Output with 1, 0 and -1:
zend.assertions: 1
bool(true)
zend.assertions: 0
bool(false)
zend.assertions: -1
bool(false)
This is useful for enabling extra debug-only work, like collecting statistics or checking a cache against the real data.
Expensive checks are free in production
Because the expression isn't evaluated when assertions are off, you can afford checks that would be far too slow to leave in production code. Binary search requires a sorted array. Checking that is O(n), which destroys the O(log n) advantage of the search, but as an assertion it's fine:
<?php
function isSorted(array $a): bool
{
for ($i = 1, $n = count($a); $i < $n; $i++) {
if ($a[$i - 1] > $a[$i]) {
return false;
}
}
return true;
}
function binarySearch(array $sorted, int $needle): int
{
assert(isSorted($sorted), 'binarySearch() needs a sorted array');
$lo = 0;
$hi = count($sorted) - 1;
while ($lo <= $hi) {
$mid = intdiv($lo + $hi, 2);
if ($sorted[$mid] === $needle) return $mid;
if ($sorted[$mid] < $needle) $lo = $mid + 1; else $hi = $mid - 1;
}
return -1;
}
$data = range(0, 20_000, 2);
$start = hrtime(true);
for ($i = 0; $i < 2_000; $i++) {
binarySearch($data, 1234);
}
printf("zend.assertions=%2s: %7.1f ms\n", ini_get('zend.assertions'), (hrtime(true) - $start) / 1e6);
Output of three runs:
zend.assertions= 1: 502.2 ms
zend.assertions= 0: 1.4 ms
zend.assertions=-1: 1.3 ms
During development and tests every call verifies its precondition. In production the check vanishes.
Never put side effects in assertions
The flip side of "the expression isn't evaluated" is that any work done inside assert() disappears in production. This is the most common assertion bug:
<?php
$queue = ['job1', 'job2', 'job3'];
// BAD: the work happens inside assert()
assert(array_shift($queue) !== null);
echo "queue after bad version: ", implode(',', $queue), "\n";
// GOOD: do the work, then assert on the result
$queue = ['job1', 'job2', 'job3'];
$job = array_shift($queue);
assert($job !== null);
echo "queue after good version: ", implode(',', $queue), "\n";
Output with zend.assertions=1:
queue after bad version: job2,job3
queue after good version: job2,job3
Output with zend.assertions=-1:
queue after bad version: job1,job2,job3
queue after good version: job2,job3
The bad version works in development and silently breaks in production. The asserted expression must only read state, never change it. (The assertionsEnabled() trick above is the one deliberate exception: its side effect exists precisely to detect whether assertions run.)
Class invariants
An invariant is a condition that must hold for an object after every public method finishes. Writing it as a private method and asserting it at the end of each mutating method catches bugs as soon as one of the methods breaks it:
<?php
final class BankAccount
{
private int $balance = 0;
private array $history = [];
public function deposit(int $amount): void
{
if ($amount <= 0) {
throw new InvalidArgumentException("deposit must be positive, got $amount");
}
$this->balance += $amount;
$this->history[] = $amount;
assert($this->invariant());
}
public function withdraw(int $amount): void
{
if ($amount > $this->balance) {
throw new RuntimeException("insufficient funds");
}
$this->balance -= $amount;
$this->history[] = -$amount;
assert($this->invariant());
}
public function applyFee(int $fee): void
{
$this->balance -= $fee; // bug: fee not recorded in history
assert($this->invariant(), "balance $this->balance does not match history");
}
public function balance(): int
{
return $this->balance;
}
private function invariant(): bool
{
return $this->balance >= 0
&& $this->balance === array_sum($this->history);
}
}
$acc = new BankAccount();
$acc->deposit(100);
$acc->withdraw(30);
echo $acc->balance(), "\n";
try {
$acc->deposit(-5);
} catch (InvalidArgumentException $e) {
echo "rejected: ", $e->getMessage(), "\n";
}
try {
$acc->applyFee(2);
} catch (AssertionError $e) {
echo "bug detected: ", $e->getMessage(), "\n";
}
Output:
70
rejected: deposit must be positive, got -5
bug detected: balance 68 does not match history
Notice the split between the two kinds of checks:
- A negative deposit comes from the caller, possibly from user input. It's checked with
if+throwand is rejected in production too. - The invariant can only fail if
BankAccountitself has a bug. It's an assertion, verified in development and free in production.
Assertions and static analysis
Static analysers like PHPStan and Psalm, and IDEs like PhpStorm, understand assert(). After assert($x instanceof Foo) or assert($x !== null) they treat $x as narrowed to that type, which removes "possibly null" warnings without changing runtime behaviour in production:
<?php
final class User
{
public function __construct(public string $name) {}
}
function findUser(array $users, int $id): ?User
{
return $users[$id] ?? null;
}
$users = [7 => new User('Alice')];
$user = findUser($users, 7);
assert($user instanceof User);
echo $user->name, "\n";
Output:
Alice
Use this only when you know the value can't be null at that point (for example, you just inserted it). If null is a legitimate outcome, such as a user id coming from a request, handle it with an if.
When to use assert() and when to throw
| Situation | Use |
|---|---|
| Invalid user input, request data, config file | if + throw (validation) |
| File missing, database down, API timeout | exceptions |
| Public library function receives a bad argument | throw new InvalidArgumentException |
| Internal helper called with impossible arguments | assert() |
| Object state that must hold after every method | assert() invariant |
| "This branch can never be reached" | throw new LogicException (always on) |
| Expensive consistency check (sortedness, totals match) | assert() |
The rule: if the condition can be false while the program is correct, it's not an assertion. And if the program must not continue even in production when the check fails (for example, it would corrupt data or charge a customer twice), use an exception that always runs.
Assertions in tests and CI
Assertions only help if they actually run while you exercise the code. Make sure zend.assertions=1 in your local php.ini and in CI. PHPUnit can tell you if it's not:
$ vendor/bin/phpunit --check-php-configuration
The Testing in CI article shows how to set it in a GitHub Actions workflow. Note that PHPUnit's own $this->assertSame() and friends are unrelated to assert(): they are test assertions that always run inside test methods, see Unit Testing.
Deprecated assertion settings
Older PHP versions had several other ini settings and the assert_options() function to configure assertions: assert.active, assert.exception, assert.warning, assert.bail and assert.callback. They date from the time when assert() emitted a warning instead of throwing, and even accepted a string of code to eval() (removed in PHP 8.0).
Since PHP 8.3 all of them are deprecated:
<?php
ini_set('assert.exception', '0');
assert_options(ASSERT_ACTIVE, 1);
echo "after\n";
Output:
Deprecated: ini_set(): assert.exception INI setting is deprecated in ...\b4.php on line 2
Deprecated: Constant ASSERT_ACTIVE is deprecated since 8.3, as assert_options() is deprecated in ...\b4.php on line 3
Deprecated: Function assert_options() is deprecated since 8.3 in ...\b4.php on line 3
after
In modern code, leave these at their defaults and use only zend.assertions. To react to failed assertions (logging, for example), catch AssertionError or Throwable in your global exception handler instead of using assert.callback.
Summary
assert($condition)throwsAssertionErrorwhen$conditionis false; the message defaults to the asserted code.- The second argument is a custom message string or a
Throwableto throw instead. AssertionErrorextendsError, socatch (Exception $e)doesn't catch it.zend.assertions=1in development and CI,-1in production; at-1assertions are not even compiled.- The asserted expression and message aren't evaluated when assertions are off: expensive checks are free, side effects are bugs.
- Use assertions for conditions that are false only if your code has a bug; use exceptions for everything else.