PHPackages                             jdecool/optional - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. jdecool/optional

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

jdecool/optional
================

A PHP implementation of the Optional pattern, inspired by Java's java.util.Optional

08PHPCI passing

Since Jan 30Pushed 1y ago1 watchersCompare

[ Source](https://github.com/jdecool/optional)[ Packagist](https://packagist.org/packages/jdecool/optional)[ RSS](/packages/jdecool-optional/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Optional
========

[](#optional)

A PHP implementation of the Optional pattern, inspired by Java's [`java.util.Optional`](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html).

This library provides a container object which may or may not contain a non-null value, helping to avoid null pointer exceptions and improve code readability.

Installation
------------

[](#installation)

### Using Composer (recommended)

[](#using-composer-recommended)

You can install this library using Composer. Run the following command in your project directory:

```
composer require jdecool/optional
```

### Manual Installation

[](#manual-installation)

If you're not using Composer, you can download the library files and include them manually in your project. Make sure to set up the appropriate autoloading for the `JDecool\DataStructure` namespace.

Usage
-----

[](#usage)

### Creating an Optional

[](#creating-an-optional)

#### `Optional::of($value)`

[](#optionalofvalue)

Creates an Optional with a non-null value.

```
use JDecool\DataStructure\Optional;

$optional = Optional::of('Hello, World!');
```

#### `Optional::ofNullable($value)`

[](#optionalofnullablevalue)

Creates an Optional that may contain a null value.

```
$optional = Optional::ofNullable(null);
```

#### `Optional::empty()`

[](#optionalempty)

Creates an empty Optional.

```
$emptyOptional = Optional::empty();
```

### Checking the Optional's State

[](#checking-the-optionals-state)

#### `ifPresent(callable $action)`

[](#ifpresentcallable-action)

Performs an action if the Optional contains a non-null value;

```
$optional->ifPresent(static fn ($value) => echo "Optional contains a value.");
```

#### `ifPresentOrElse(callable $action, callable $emptyAction)`

[](#ifpresentorelsecallable-action-callable-emptyaction)

Performs the given action with the value, otherwise performs the given empty-based action.

```
$optional->ifPresentOrElse(
  static fn ($value) => echo "Optional contains a value.",
  static fn () => echo "Optional doesn't contains a value.",
);
```

#### `isPresent()`

[](#ispresent)

Checks if the Optional contains a non-null value.

```
if ($optional->isPresent()) {
    echo "Value is present";
}
```

#### `isEmpty()`

[](#isempty)

Checks if the Optional is empty (contains null).

```
if ($optional->isEmpty()) {
    echo "Optional is empty";
}
```

### Retrieving the Value

[](#retrieving-the-value)

#### `get()`

[](#get)

Retrieves the value if present, throws a `NoSuchElementException` if empty.

```
try {
    $value = $optional->get();
} catch (NoSuchElementException $e) {
    echo "No value present";
}
```

### Transforming and Filtering

[](#transforming-and-filtering)

#### `filter(callable $predicate)`

[](#filtercallable-predicate)

Filters the Optional based on a predicate.

```
$filtered = $optional->filter(fn($value) => strlen($value) > 5);
```

#### `map(callable $mapper)`

[](#mapcallable-mapper)

Transforms the Optional's value using a mapping function.

```
$mapped = $optional->map(fn($value) => strtoupper($value));
```

### Providing Fallback Values

[](#providing-fallback-values)

#### `or($other)`

[](#orother)

Returns the Optional if it has a value, otherwise returns the provided Optional.

```
$result = $optional->or(Optional::of('Default'));
```

#### `orElse($other)`

[](#orelseother)

Returns the Optional's value if present, otherwise returns the provided value.

```
$value = $optional->orElse('Default');
```

#### `public function orElseGet(callable $supplier)`

[](#public-function-orelsegetcallable-supplier)

Returns the Optional's value if present, otherwise returns the result of the callable.

```
$value = $optional->orElseGet(fn() => 'Default');
```

#### `orElseThrow(Throwable $exception)`

[](#orelsethrowthrowable-exception)

Returns the Optional's value if present, otherwise throws the provided exception.

```
try {
    $value = $optional->orElseThrow(new Exception('Value not present'));
} catch (Exception $e) {
    echo $e->getMessage();
}
```

### Comparing Optionals

[](#comparing-optionals)

#### `equals(mixed $object)`

[](#equalsmixed-object)

Compares this Optional to another object for equality.

```
$isEqual = $optional->equals(Optional::of('Hello, World!'));
```

This Optional library provides a robust way to handle potentially null values in your PHP code, reducing the risk of null pointer exceptions and improving overall code quality.

###  Health Score

15

—

LowBetter than 3% of packages

Maintenance32

Infrequent updates — may be unmaintained

Popularity4

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity16

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/a648f4457ad94c2fc48782bded875f3bf051b480fd2fe01eb7654b9fab180e5e?d=identicon)[jdecool](/maintainers/jdecool)

---

Top Contributors

[![jdecool](https://avatars.githubusercontent.com/u/433926?v=4)](https://github.com/jdecool "jdecool (17 commits)")

### Embed Badge

![Health badge](/badges/jdecool-optional/health.svg)

```
[![Health](https://phpackages.com/badges/jdecool-optional/health.svg)](https://phpackages.com/packages/jdecool-optional)
```

###  Alternatives

[fisharebest/ext-calendar

Implementation of the Arabic (Hijri), French, Gregorian, Jewish, Julian and Persian (Jalali) calendars. Also provides a replacement for the PHP ext/calendar extension.

36473.2k8](/packages/fisharebest-ext-calendar)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
