# Union Types

> Section in “Beyond PHP 7.4” of the book [PHP 7 Explained](https://php7explained.com/) by Sebastian Bergmann and Stefan Priebsch, published by thePHP.cc. The book covers PHP 7.0 to 7.4 and was last updated in November 2020. HTML version: <https://php7explained.com/beyond-php-7.4/union-types/>

A parameter or return value that is declared using a union type such as `bool|int` allows multiple, different types for its values rather than just a single type. Prior to PHP 8, the language already had limited support for union types for special cases:

- `?Type` to denote that values of type `Type` are allowed as well as `null` (see the “[Nullable Types](https://php7explained.com/new-and-extended-functionality/type-system/nullable-types/)” section)
- `iterable` to denote that values of type `array` and `Traversable` are allowed (see the “[The `Iterable` Type](https://php7explained.com/new-and-extended-functionality/type-system/the-iterable-type/)” section)
- `catch (FooException|BarException $e)` to denote that a `catch` block can handle exceptions of type `FooException` as well as `BarException` (see the “[Handling Multiple Exception Types with one `catch` Statement](https://php7explained.com/new-and-extended-functionality/error-handling/handling-multiple-exception-types-with-one-catch-statement/)” section

PHP 8 introduces full support for union types to all places where types can be declared. Here is an example of a function, `f()`, that uses a union type in the declaration of its parameter:

``` php
function f(bool|int $a): void
{
    var_dump($a);
}
```

The function shown above declares that it accepts values of type `bool` or `int` as arguments for its `$a` parameter. Below you can see how `f()` behaves when scalar types are not interpreted strictly:

``` php
f(false);         // Will print bool(false)
f(true);          // Will print bool(true)
f(0);             // Will print int(0)
f(1);             // Will print int(1)
f(1.2);           // Will print int(1)
f('1234');        // Will print int(1234)
f('1234abcd');    // Will print int(1234) and trigger a notice
f('');            // Will print bool(false)
f('a');           // Will print bool(true)
f(new stdClass);  // Will result in a type error
```

Below you can see how `f()` behaves when scalar types are interpreted strictly:

``` php
f(false);         // Will print bool(false)
f(true);          // Will print bool(true)
f(0);             // Will print int(0)
f(1);             // Will print int(1)
f(1.2);           // Will result in a type error
f('1234');        // Will result in a type error
f('1234abcd');    // Will result in a type error
f('');            // Will result in a type error
f('a');           // Will result in a type error
f(new stdClass);  // Will result in a type error
```

---

Previous: [Attributes](https://php7explained.com/beyond-php-7.4/attributes/index.html.md) | Next: [mixed Type](https://php7explained.com/beyond-php-7.4/mixed-type/index.html.md)
