PHPackages                             jimmyoak/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. jimmyoak/optional

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

jimmyoak/optional
=================

2.2.0(9y ago)86.8k[1 issues](https://github.com/jimmyoak/optional/issues)MITPHPPHP &gt;=7.0

Since Aug 8Pushed 9y ago1 watchersCompare

[ Source](https://github.com/jimmyoak/optional)[ Packagist](https://packagist.org/packages/jimmyoak/optional)[ RSS](/packages/jimmyoak-optional/feed)WikiDiscussions master Synced today

READMEChangelogDependencies (1)Versions (8)Used By (0)

Optional
========

[](#optional)

A port of Java 9's java.util.Optional improved for PHP.

Some examples
-------------

[](#some-examples)

### Basic usage

[](#basic-usage)

Example request class:

```
class Request
{
    private $date;
    // ... constructor and getter ...
}
```

Example code of optional:

```
$date = Optional::ofNullable($request->getDate())
    ->map(function ($dateString) {
        return DateTime::createFromFormat('Y-m-d', $dateString);
    })
    ->orElseGet(function () {
        return new \DateTime();
    });

echo $date->format('Y-m-d');
```

Given this request:

```
$request = new Request('1992-10-07');
```

Program will output `1992-10-07`.

If a null is specified in request:

```
$request = new Request(null);
```

Then program will output the default value, which in this case would be something like `2016-08-19`

Instead of returning a default value we could just throw an exception in case no value:

```
$date = Optional::ofNullable($request->getDate())
    ->map(function ($dateString) {
        return DateTime::createFromFormat('Y-m-d', $dateString);
    })
    ->orElseThrow(new \Exception());
```

In case of:

```
$request = new Request(null);
```

Program will throw the specified exception, otherwise, will return specified parsed date.

### or

[](#or)

We can chain Optionality:

```
$findInMemory = function () {
    ...
    return Optional::ofNullable(...);
};

$findInDisc = function () {
    ...
    return Optional::ofNullable(...);
};

$findRemotely = function () {
    ...
    return Optional::ofNullable(...);
};

$optional = $findInMemory()
    ->or($findInDisc)
    ->or($findRemotely);
```

Callbacks will only execute if the last optional is empty. Example:

```
$findInMemory = function () {
    echo "Searching in memory...\n";
    return Optional::empty();
};

$findInDisc = function () {
    echo "Searching in disc...\n";
    return Optional::of("Awesome");
};

$findRemotely = function () {
    echo "Searching remotely...";
    return Optional::of("Not so awesome");
};

$findInMemory()
    ->or($findInDisc)
    ->or($findRemotely)
    ->ifPresent(function ($value) {
        echo $value;
    });
```

Will output:

```
Searching in memory...
Searching in disc...
Awesome

```

### filter

[](#filter)

```
$request = new Request('1992-10-07');

$makeDateTime = function ($value) {
    return \DateTime::createFromFormat('Y-m-d', $value);
};

$beforeNow = function (\DateTime $date) {
    return $date->getTimestamp() > (new \DateTime())->getTimestamp();
};

$date = Optional::ofNullable($request->getDate())
    ->map($makeDateTime)
    ->filter($beforeNow)
    ->orElse(new \DateTime());

echo $date->format('Y-m-d');
```

Outputs (similar): `2016-08-19`

With: `$request = new Request('2030-01-01');` would output: `2030-01-01`

With: `$request = new Request(null);` would output: `2016-08-19`

### ifPresent

[](#ifpresent)

```
Optional::ofNullable($request->getDate())
    ->ifPresent(function ($value) {
        echo "It's present: " . $value;
    });
```

If value, it would output: `It's present: 1992-10-07`Otherwise would do nothing.

### ifPresentOrElse

[](#ifpresentorelse)

Similar to ifPresent but with an else callback if optional is empty

```
Optional::ofNullable($request->getDate())
    ->ifPresentOrElse(function ($value) {
        echo "It's present: " . $value;
    }, function() {
        echo 'No value is present';
    });
```

If value, it would output: `It's present: 1992-10-07`Otherwise, it would output: `No value is present`

### Comparable

[](#comparable)

Returns true:

```
Optional::of('something')->equals(Optional::of('something'));
```

Returns false:

```
Optional::of(5)->equals(Optional::of('something'));
```

Returns true:

```
Optional::empty()->equals(Optional::empty());
```

Returns false:

```
Optional::empty()->equals(Optional::of(5));
```

### \_\_toString

[](#__tostring)

```
echo (string) Optional::of('something');
```

Outputs: `Optional[something]`

```
echo (string) Optional::empty();
```

Outputs: `Optional.empty`

###  Health Score

31

—

LowBetter than 66% of packages

Maintenance18

Infrequent updates — may be unmaintained

Popularity23

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity63

Established project with proven stability

 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.

###  Release Activity

Cadence

Every ~13 days

Total

7

Last Release

3531d ago

Major Versions

1.2.1 → 2.0.02016-10-28

### Community

Maintainers

![](https://www.gravatar.com/avatar/78fab774f12b9fcbee507458659c59fe18b691dd5033a0f0528f9f7e14f38eef?d=identicon)[jimmyoak](/maintainers/jimmyoak)

---

Top Contributors

[![jimmyoak](https://avatars.githubusercontent.com/u/7147129?v=4)](https://github.com/jimmyoak "jimmyoak (16 commits)")

---

Tags

utiljimmyjimmyoakutilitiesoptionaloptionals

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[vaimo/composer-patches

Applies a patch from a local or remote file to any package that is part of a given composer project. Patches can be defined both on project and on package level. Optional support for patch versioning, sequencing, custom patch applier configuration and patch command for testing/troubleshooting added patches.

3014.5M22](/packages/vaimo-composer-patches)[lodash-php/lodash-php

A port of Lodash to PHP

524741.7k5](/packages/lodash-php-lodash-php)[kartik-v/yii2-helpers

A collection of useful helper functions for Yii Framework 2.0

883.1M29](/packages/kartik-v-yii2-helpers)[longman/ip-tools

PHP IP Tools for manipulation with IPv4 and IPv6

147253.5k7](/packages/longman-ip-tools)[mathiasverraes/classfunctions

Functions to manipulate class names

34485.8k10](/packages/mathiasverraes-classfunctions)[jansenfelipe/utils

Uma simples classe utilitária com métodos que podem salvar sua vida (ou não)

61150.9k10](/packages/jansenfelipe-utils)

PHPackages © 2026

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