PHPackages                             zicht/itertools - 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. zicht/itertools

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

zicht/itertools
===============

A collection of functions that mirror the Python itertools library

3.0.3(2y ago)1027.6k1[5 issues](https://github.com/zicht/itertools/issues)MITPHPPHP ^7.4 || ^8.0CI failing

Since Jul 22Pushed 2y ago5 watchersCompare

[ Source](https://github.com/zicht/itertools)[ Packagist](https://packagist.org/packages/zicht/itertools)[ RSS](/packages/zicht-itertools/feed)WikiDiscussions release/3.x Synced today

READMEChangelogDependencies (5)Versions (106)Used By (0)

[![Build Status](https://camo.githubusercontent.com/5b565d35436f188c57557eab289705bfbf52e2ab93b8136942a83baff94dc50f/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f7a696368742f69746572746f6f6c732f6261646765732f6275696c642e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/zicht/itertools/build-status/master)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/120e0ed4a4232df85b06c89c3e3fc8181f9de9e28615784573ec6d61a08bc999/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f7a696368742f69746572746f6f6c732f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/zicht/itertools/?branch=master)[![Code Coverage](https://camo.githubusercontent.com/71abafdcd2143726e8d6b954fadf900486e6d882f70fbc5ccad60e83e0640cf3/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f7a696368742f69746572746f6f6c732f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/zicht/itertools/?branch=master)

Zicht Iterator Tools Library
============================

[](#zicht-iterator-tools-library)

The Iterator Tools, or itertools for short, are a collection of convenience tools to handle sequences of data such as arrays, iterators, and strings. Some of the naming and API is based on the Python itertools.

[Examples](#examples)

Common operations include:

- [mapping](#mapping): `map` and `mapBy`
- [filtering](#filtering): `filter`, `difference`
- [sorting](#sorting): `sorted`
- [grouping](#grouping): `groupBy`
- [reducing](#reducing): `accumulate`, `collapse`, and `reduce`

Usage
-----

[](#usage)

In order to use the available itertools filters/functions via Twig, simply add this service definition in your `config/services.yaml`

```
Zicht\Itertools\twig\Extension:
  tags: ['twig.extension']
```

Scripts
-------

[](#scripts)

- unit test: `composer test`
- lint test: `composer lint`

Example data
------------

[](#example-data)

The examples below will use the following data to illustrate how various Iterator tools work:

```
$words = ['Useful', 'Goonies', 'oven', 'Bland', 'notorious'];
$numbers = [1, 3, 2, 5, 4];
$vehicles = [
    [
        'id' => 1,
        'type' => 'car',
        'wheels' => 4,
        'colors' => ['red', 'green', 'blue'],
        'is_cool' => false,
        'price' => 20000,
    ],
    [
        'id' => 2,
        'type' => 'bike',
        'wheels' => 2,
        'colors' => ['red', 'green', 'blue'],
        'is_cool' => false,
        'price' => 600,
    ],
    [
        'id' => 5,
        'type' => 'unicicle',
        'wheels' => 1,
        'colors' => ['red'],
        'is_cool' => true,
        'price' => 150,
    ],
    [
        'id' => 9,
        'type' => 'car',
        'wheels' => 8,
        'colors' => ['blue'],
        'is_cool' => true,
        'price' => 100000,
    ],
];
```

Examples
--------

[](#examples)

With the example data above, this is how you could use itertools to get all unique colors of the cars in alphabetical order:

```
use Zicht\Itertools\util\Filters;
use function Zicht\Itertools\iterable;

$vehicles = iterable($vehicles)
    ->filter(Filters::equals('car', 'type')) // {[vehicle...], [vehicle...]}
    ->map('colors') // {0: ['red', 'green', 'blue'], 1: ['blue']}
    ->collapse() // {0: 'red', 1: 'green', 2: 'blue', 3: 'blue'}
    ->unique() // {0: 'red', 1: 'green', 2: 'blue'}
    ->sorted(); // {2: 'blue', 1: 'green', 0: 'red'}
```

You can achieve the same in Twig:

```
{% for vehicle_color in vehicles
    |it.filter(it.filters.equals('car', 'type'))
    |it.map('colors')
    |it.collapse
    |it.unique
    |it.sorted
%}
    {{ vehicle_color }}
{% endfor %}
```

Getter strategy
---------------

[](#getter-strategy)

Many itertools can be passed a `$strategy` parameter. This parameter is used to obtain a value from the elements in the collection. The `$strategy` can be one of three things:

1. null, in which case the element itself is returned. For example:

    ```
    use function Zicht\Itertools\iterable;

    $result = iterable($words)->map(null);
    var_dump($result);
    // {0: 'Useful', 1: 'Goonies', 2: 'oven', 3: 'Bland', 4: 'notorious'}
    ```

    Or in Twig:

    ```
    {{ dump(word|it.map) }}
    ```
2. a closure, in which case the closure is called with the element value and key as parameters to be used to compute a return value. For example:

    ```
    use function Zicht\Itertools\iterable;

    $getDouble = fn($value, $key) => 2 * $value;
    $result = iterable($numbers)->map($getDouble);
    var_dump($result);
    // {0: 2, 1: 6, 2: 4, 3: 10, 4: 8}
    ```

    Or in Twig:

    ```
    {{ dump(numbers|it.map(num => 2 * num)) }}
    ```
3. a string, in which case this string is used to create a closure that tries to find public properties, methods, or array indexes. For example:

    ```
    use function Zicht\Itertools\iterable;

    $result = iterable($vehicles)->map('type');
    var_dump($result);
    // {0: 'car', 1: 'bike', 2: 'unicicle', 3: 'car'}
    ```

    Or in Twig:

    ```
    {{ dump(word|it.map) }}
    ```

    The string can consist of multiple dot separated words, allowing access to nested properties, methods, and array indexes.

    If one of the words in the string can not be resolved into an existing property, method, or array index, the value `null` will be returned. For example:

    ```
    use function Zicht\Itertools\iterable;

    $result = iterable($vehicles)->map('colors.2');
    var_dump($result);
    // {0: 'blue', 1: 'blue', 2: null, 3: null}
    ```

    Or in Twig:

    ```
    {{ dump(vehicles|it.map('colors.2')) }}
    ```

Fluent interface
----------------

[](#fluent-interface)

One way to use the Iterator Tools is to convert the array, Iterator, string, etc into an `IterableIterator`. This class provides a fluent interface to all of the common operations. For example:

```
use function Zicht\Itertools\iterable;

$result = iterable($vehicles)->filter('is_cool')->mapBy('id')->map('type');
var_dump($result);
// {5: 'unicicle', 9: 'car'}
```

Or in Twig:

```
{{ dump(vehicles|it.filter('is_cool').mapBy('id').map('type')) }}
```

Mapping
-------

[](#mapping)

Mapping converts one collection into another collection of equal length. Using `map` allows manipulation of the elements while `mapBy`allows manipulation of the collection keys.

For example, we can use a closure to create a title for each element in `$vehicles`:

```
use function Zicht\Itertools\iterable;

$getTitle = fn($value, $key) => sprintf('%s with %s wheels', $value['type'], $value['wheels']);
$titles = iterable($vehicles)->map($getTitle);
var_dump($titles);
// {0: 'car with 4 wheels', ..., 3: 'car with 8 wheels'}
```

Using the string [getter strategy](#getter-strategy) we can easily get the types for each element in `$vehicles` mapped by the vehicle identifiers. For example:

```
use function Zicht\Itertools\iterable;

$types = iterable($vehicles)->mapBy('id')->map('type');
var_dump($types);
// {1: 'car', 2: 'bike', 5: 'unicicle', 9: 'car'}
```

Or in Twig:

```
{{ dump(vehicles|it.mapBy('id').map('type')) }}
```

There are several common mapping closures available in [mappings.php](src/Zicht/Itertools/util/Mappings.php). Calling these functions returns a closure that can be passed to `map` and `mapBy`. For example:

```
use Zicht\Itertools\util\Mappings;
use function Zicht\Itertools\iterable;

$lengths = iterable($words)->map(Mappings::length());
var_dump($lengths);
// {0: 6, 1: 3, 2: 4, 3: 5, 4: 9}
```

Or in Twig:

```
{{ dump(words|it.map(it.mappings.length)) }}
```

Filtering
---------

[](#filtering)

Filtering converts one collection into another, possibly shorter, collection. Using `filter` each element in the collection is evaluated, the elements that are considered `empty` will be rejected, while the elements that are not `empty` will be allowd to pass through the filter.

For example, we can use a closure to determine if an element is expensive, the `filter` will then only allow the expensive elements through:

```
use function Zicht\Itertools\iterable;

$isExpensive = fn($value, $key) => $value['price'] >= 10000;
$expensiveTypes = iterable($vehicles)->filter($isExpensive)->map('type');
var_dump($expensiveTypes);
// {1: 'car', 9: 'car'}
```

Or in Twig:

```
{{ dump(vehicles|it.filter(vehicle => vehicle.price >= 10000).map('type')) }}
```

Using the string [getter strategy](#getter-strategy) we can get only the `$vehicles` that are considered to be cool. For example:

```
use function Zicht\Itertools\iterable;

$coolVehicleTypes = iterable($vehicles)->filter('is_cool')->map('type');
var_dump($coolVehicleTypes);
// {5: 'unicicle', 9: 'car'}
```

Or in Twig:

```
{{ dump(vehicles|it.filter('is_cool').map('type')) }}
```

There are several common filter closures available in [filters.php](src/Zicht/Itertools/util/Filters.php). Calling these function returns a closure that can be passed to `filter`. For example:

```
use Zicht\Itertools\util\Filters;
use function Zicht\Itertools\iterable;

$movieWords = iterable($words)->filter(Filters::in(['Shining', 'My little pony', 'Goonies']));
var_dump($movieWords);
// {1: 'Goonies'}
```

Or in Twig:

```
{{ dump(words|it.filter(it.filters.in(['Shining', "My little pony', 'Goonies'])) }}
```

Sorting
-------

[](#sorting)

`sorted` converts one collection into another collection of equal size but with the elements possibly reordered.

For example, using the `null` [getter strategy](#getter-strategy), which is the default, we will sort using the element values in ascending order:

```
use function Zicht\Itertools\iterable;

$ordered = iterable($numbers)->sorted();
var_dump($ordered);
// {0: 1, 2: 2, 1: 3, 4: 4, 3: 5}
```

Or in Twig:

```
{{ dump(numbers|it.sorted }}
```

The sorting algorithm will preserve the keys and is guaranteed to be stable. I.e. when elements are sorted using the same value, then the sorted order is guaranteed to be the same as the order of the input elements. This is contrary to the standard PHP sorting functions.

Using the closure [getter strategy](#getter-strategy) the returned value is used to determine the order. The closure is called exactly once per element, and the resulting values must be comparable. For example:

```
use function Zicht\Itertools\iterable;

$getLower = fn($value, $key) => strtolower($value);
$ordered = iterable($words)->sorted($getLower);
var_dump($ordered);
// {3: 'Bland', 1: 'Goonies', 2: 'oven', 0: 'Useful', 4: 'notorious'};
```

The [mappings.php](src/Zicht/Itertools/util/Mappings.php) provides a mapping closure which returns a random number. This can be used to sort a collection in a random order. For example:

```
use Zicht\Itertools\util\Mappings;
use function Zicht\Itertools\iterable;

$randomized = iterable($words)->sorted(Mappings::random());
var_dump($randomized);
// {... randomly ordere words ...}
```

Or in Twig:

```
{{ dump(words|it.sorted(it.mappings.random)) }}
```

Grouping
--------

[](#grouping)

`groupBy` converts one collection into one or more collections that group the elements together on a specific criteria.

For example, using the string [getter strategy](#getter-strategy) we can group all the `$vehicles` of the same type together:

```
use function Zicht\Itertools\iterable;

$vehiclesByType = iterable($vehicles)->groupBy('type');
var_dump($vehiclesByType);
// {'bike': {1: [...]}, 'car': {0: [...], 3: [...]} 'unicicle': {2: [...]}}
```

Or in Twig:

```
{{ dump(vehicles|it.groupBy('type')) }}
```

Not that the original keys of the vehicles are still part of the resulting groups, and the elements within each group keep the order that they had in the input, i.e. it uses the stable sorting provided by [`sorted`](#sorting).

Reducing
--------

[](#reducing)

`reduce` converts a collection into a single value by calling a closure of two arguments cumulatively to the elements in the collection, from left to right.

For example, without any arguments `reduce` will add all elements of the collection together:

```
use function Zicht\Itertools\iterable;

$sum = iterable($numbers)->reduce();
var_dump($sum);
// 15
```

Or in Twig:

```
{{ dump(numbers|it.reduce) }}
```

In the above example, the default closure that is used looks like this:

```
public static function add($a, $b): \Closure
{
    return $a + $b;
}
```

Given that `$numbers` consists of the elements {1, 3, 2, 5, 4}, the `add` closure is called four times:

```
$sum = Reductions::add(Reductions::add(Reductions::add(Reductions::add((1, 3), 2), 5), 4));
var_dump($sum);
// 15
```

There are several common reduction closures available in [reductions.php](src/Zicht/Itertools/util/Reductions.php). Calling these functions returns a closure that can be passed to `reduction`. For example:

```
use Zicht\Itertools\util\Reductions;
use function Zicht\Itertools\iterable;

$scentence = iterable($words)->reduce(Reductions::join(' - '));
var_dump($scentence);
// 'Useful - Goonies - oven - Bland - notorious'
```

Or in Twig:

```
{{ dump(words|it.reduce(it.reductions.join(' - ')) }}
```

Another common reduction is chaining multiple lists together into one list. We call this process collapse. This process can also be achieved using `reduce`and `chain` together, however, because it is used frequently the `collapse` helper makes its usage easier, for example:

```
use function Zicht\Itertools\iterable;

$flat = iterable([['one', 'two'], ['three']])->collapse();
var_dump($flat);
// {0: 'one', 1: 'two', 0: 'three'}
```

Or in Twig:

```
{% set data = [['one', 'two'], ['three']] %}
{{ dump(data|it.collapse) }}
```

Maintainer(s)
=============

[](#maintainers)

- Boudewijn Schoon
- Virginia Meijer

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance10

Infrequent updates — may be unmaintained

Popularity30

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity85

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 83.5% 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 ~27 days

Recently: every ~189 days

Total

104

Last Release

1049d ago

Major Versions

1.5.0 → 2.0.0-beta.12016-03-07

2.15.0 → 3.0.02021-10-21

PHP version history (2 changes)2.14.0PHP ^5.6 || ^7.0

3.0.0PHP ^7.4 || ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/06a59c100a4b131574c214b7ad396a6f8ce1a4a261e4d4a7dd525ba562652346?d=identicon)[zicht-jenkins](/maintainers/zicht-jenkins)

---

Top Contributors

[![boudewijn-zicht](https://avatars.githubusercontent.com/u/22885475?v=4)](https://github.com/boudewijn-zicht "boudewijn-zicht (258 commits)")[![VMeijer-Zicht](https://avatars.githubusercontent.com/u/57255942?v=4)](https://github.com/VMeijer-Zicht "VMeijer-Zicht (16 commits)")[![muhammedeminakbulut](https://avatars.githubusercontent.com/u/8781648?v=4)](https://github.com/muhammedeminakbulut "muhammedeminakbulut (8 commits)")[![erik-zicht](https://avatars.githubusercontent.com/u/33859362?v=4)](https://github.com/erik-zicht "erik-zicht (8 commits)")[![ErikTrapman](https://avatars.githubusercontent.com/u/1147578?v=4)](https://github.com/ErikTrapman "ErikTrapman (5 commits)")[![7ochem](https://avatars.githubusercontent.com/u/2794908?v=4)](https://github.com/7ochem "7ochem (3 commits)")[![drm](https://avatars.githubusercontent.com/u/154580?v=4)](https://github.com/drm "drm (3 commits)")[![skarnl](https://avatars.githubusercontent.com/u/3471506?v=4)](https://github.com/skarnl "skarnl (3 commits)")[![wtfzdotnet](https://avatars.githubusercontent.com/u/639376?v=4)](https://github.com/wtfzdotnet "wtfzdotnet (2 commits)")[![peerknife](https://avatars.githubusercontent.com/u/30040959?v=4)](https://github.com/peerknife "peerknife (2 commits)")[![rikvanderkemp](https://avatars.githubusercontent.com/u/347308?v=4)](https://github.com/rikvanderkemp "rikvanderkemp (1 commits)")

---

Tags

closurefilterfluent-interfaceiteratoritertoolsmanipulationpackagistphpphp-librarysort

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/zicht-itertools/health.svg)

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

###  Alternatives

[uccellolabs/filament-theme-color

Easy way to change filament theme color on the fly.

1717.0k](/packages/uccellolabs-filament-theme-color)

PHPackages © 2026

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