PHPackages                             jotaelesalinas/php-mapreduce - 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. jotaelesalinas/php-mapreduce

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

jotaelesalinas/php-mapreduce
============================

A local implementation of the map-reduce strategy in PHP

v2.0.0(3y ago)112615[1 PRs](https://github.com/jotaelesalinas/php-mapreduce/pulls)MITPHPPHP &gt;=8.0

Since Aug 21Pushed 2y ago3 watchersCompare

[ Source](https://github.com/jotaelesalinas/php-mapreduce)[ Packagist](https://packagist.org/packages/jotaelesalinas/php-mapreduce)[ Docs](https://github.com/jotaelesalinas/php-mapreduce)[ RSS](/packages/jotaelesalinas-php-mapreduce/feed)WikiDiscussions master Synced 3w ago

READMEChangelog (10)Dependencies (2)Versions (13)Used By (0)

php-mapreduce
=============

[](#php-mapreduce)

[![Latest Version on Packagist](https://camo.githubusercontent.com/cb59f1a1d53f4c28bd7c2ddc708bc2d14573bd60498c1790f1de82e60aa193b5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6a6f7461656c6573616c696e61732f7068702d6d61707265647563652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/jotaelesalinas/php-mapreduce)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Build Status](https://camo.githubusercontent.com/44ebfd489a14374c8dc25271e48421ba27216ca0dc9094879bb3c5c347be291a/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f6a6f7461656c6573616c696e61732f7068702d6d61707265647563652f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/jotaelesalinas/php-mapreduce)[![Total Downloads](https://camo.githubusercontent.com/7580bfc3eebb614b9d7d476b80ab41968b9c77396a088b2c67ba8eb75e24b317/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6a6f7461656c6573616c696e61732f7068702d6d61707265647563652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/jotaelesalinas/php-mapreduce)

PHP PSR-4 compliant library to easily do non-distributed local map-reduce.

Install
-------

[](#install)

Via Composer

```
$ composer require jotaelesalinas/php-mapreduce
```

Basic usage
-----------

[](#basic-usage)

```
require_once __DIR__ . '/vendor/autoload.php';

$source = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$mapper = fn($item) => $item * 2;
$reducer = fn($carry, $item) => ($carry ?? 0) + $item;

$result = MapReduce\MapReduce::create()
    ->setInput($source)
    ->setMapper($mapper)
    ->setReducer($reducer)
    ->run();

print_r($result);
```

The output is:

```
Array
(
    [0] => 110
)

```

### Filters

[](#filters)

```
$odd_numbers = fn($item) => $item % 2 === 0;
$greater_than_10 = fn($item) => $item > 10;

$result = MapReduce\MapReduce::create([
        "input" => $source,
        "mapper" => $mapper,
        "reducer" => $reducer,
    ])
    // only odd numbers are passed to the mapper function
    ->setPreFilter($odd_numbers)
    // only numbers greater than 10 are passed to the reducer function
    ->setPostFilter($greater_than_10)
    ->run();

print_r($result);
```

The output is:

```
Array
(
    [0] => 48
)

```

### Groups

[](#groups)

Group by the value of a field (valid for arrays and objects):

```
$source = [
    [ "first_name" => "Susanna", "last_name" => "Connor",  "member" => "y", "age" => 20],
    [ "first_name" => "Adrian",  "last_name" => "Smith",   "member" => "n", "age" => 22],
    [ "first_name" => "Mike",    "last_name" => "Mendoza", "member" => "n", "age" => 24],
    [ "first_name" => "Linda",   "last_name" => "Duguin",  "member" => "y", "age" => 26],
    [ "first_name" => "Bob",     "last_name" => "Svenson", "member" => "n", "age" => 28],
    [ "first_name" => "Nancy",   "last_name" => "Potier",  "member" => "y", "age" => 30],
    [ "first_name" => "Pete",    "last_name" => "Adams",   "member" => "n", "age" => 32],
    [ "first_name" => "Susana",  "last_name" => "Zommers", "member" => "y", "age" => 34],
    [ "first_name" => "Adrian",  "last_name" => "Deville", "member" => "n", "age" => 36],
    [ "first_name" => "Mike",    "last_name" => "Cole",    "member" => "n", "age" => 38],
    [ "first_name" => "Mike",    "last_name" => "Angus",   "member" => "n", "age" => 40],
];

// mapper does nothing
$mapper = fn($x) => $x;

// number of persons and sum of ages
$reduceAgeSum = function ($carry, $item) {
    if (is_null($carry)) {
        return [
            'count' => 1,
            'age_sum' => $item['age'],
        ];
    }

    $count = $carry['count'] + 1;
    $age_sum = $carry['age_sum'] + $item['age'];

    return compact('count', 'age_sum');
};

$result = MapReduce\MapReduce::create([
        "input" => $source,
        "mapper" => $mapper,
        "reducer" => $reduceAgeSum,
    ])
    // group by field 'member'
    ->setGroupBy('member')
    ->run();

print_r($result);
```

The output is:

```
Array
(
    [y] => Array
        (
            [count] => 4
            [age_sum] => 110
        )

    [n] => Array
        (
            [count] => 7
            [age_sum] => 220
        )

)

```

Group by a custom value generated from each item:

```
$closestTen = fn($x) => floor($x['age'] / 10) * 10;

$result = MapReduce\MapReduce::create([
        "input" => $source,
        "mapper" => $mapper,
        "reducer" => $reduceAgeSum,
    ])
    // group by age ranges of 10
    ->setGroupBy($closestTen)
    ->run();

print_r($result);
```

The output is:

```
Array
(
    [20] => Array
        (
            [count] => 5
            [age_sum] => 120
        )

    [30] => Array
        (
            [count] => 5
            [age_sum] => 170
        )

    [40] => Array
        (
            [count] => 1
            [age_sum] => 40
        )

)

```

### Input

[](#input)

`MapReduce` accepts as input any data of type `iterable`. That means, arrays and traversables, e.g. generators.

This is very handy when reading from big files that do not fit in memory.

```
$result = MapReduce\MapReduce::create([
        "mapper" => $mapper,
        "reducer" => $reducer,
    ])
    ->setInput(csvReadGenerator('myfile.csv'))
    ->run();
```

Multiple inputs can be specified, passing several arguments to `setInput()`, as long as all of them are iterable:

```
$result = MapReduce\MapReduce::create([
        "mapper" => $mapper,
        "reducer" => $reducer,
    ])
    ->setInput($arrayData, csvReadGenerator('myfile.csv'))
    ->run();
```

### Output

[](#output)

`MapReduce` can be configured to write the final data to one or more destinations.

Each destination has to be a `Generator`:

```
$result = MapReduce\MapReduce::create([
        "mapper" => $mapper,
        "reducer" => $reducer,
    ])
    ->setOutput(csvWriteGenerator('results.csv'))
    ->run();
```

Multiple outputs can be specified as well:

```
$result = MapReduce\MapReduce::create([
        "mapper" => $mapper,
        "reducer" => $reducer,
    ])
    ->setOutput(csvWriteGenerator('results.csv'), consoleGenerator())
    ->run();
```

To help working with input and output generators, it is recommended to use the package [`jotaelesalinas/php-generators`](http://github.com/jotaelesalinas/php-generators), but it is not mandatory.

You can see more elaborated examples under the folder [examples](examples).

Change log
----------

[](#change-log)

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

Testing
-------

[](#testing)

```
$ composer test
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) and [CONDUCT](CONDUCT.md) for details.

Security
--------

[](#security)

If you discover any security related issues, please DM me to [@jotaelesalinas](http://twitter.com/jotaelesalinas) instead of using the issue tracker.

To do
-----

[](#to-do)

- Add events to help see progress in large batches
- Add docs
- Insurance example
    - adapt to new library
    - add insured values
    - improve kml output (info, markers)

Credits
-------

[](#credits)

- [José Luis Salinas](https://github.com/jotaelesalinas)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

35

—

LowBetter than 77% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity21

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity75

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 ~263 days

Recently: every ~558 days

Total

11

Last Release

960d ago

Major Versions

v0.2.1 → v1.0.02016-08-29

v1.0.5 → v2.0.0-beta.12022-07-31

PHP version history (4 changes)v0.1.0PHP &gt;=5.5

v1.0.4PHP &gt;=7.0

v1.0.5PHP &gt;=5.6

v2.0.0-beta.1PHP &gt;=8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/94935088e6eab9c315a8a07d49152d0bd4aaab1fb468d6c481408e10c95babc8?d=identicon)[jotaelesalinas](/maintainers/jotaelesalinas)

---

Top Contributors

[![jotaelesalinas](https://avatars.githubusercontent.com/u/2042875?v=4)](https://github.com/jotaelesalinas "jotaelesalinas (44 commits)")

---

Tags

phpmapreducemapreducemap-reducephp-mapreducenon-distributed

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/jotaelesalinas-php-mapreduce/health.svg)

```
[![Health](https://phpackages.com/badges/jotaelesalinas-php-mapreduce/health.svg)](https://phpackages.com/packages/jotaelesalinas-php-mapreduce)
```

###  Alternatives

[aimeos/map

Easy and elegant handling of PHP arrays as array-like collection objects similar to jQuery and Laravel Collections

4.3k443.7k14](/packages/aimeos-map)[dusank/knapsack

Collection library for PHP

5351.0M25](/packages/dusank-knapsack)[graze/data-structure

Data collections and containers

12293.1k10](/packages/graze-data-structure)[chemem/bingo-functional

A simple functional programming library.

687.0k3](/packages/chemem-bingo-functional)

PHPackages © 2026

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