PHPackages                             fusonic/linq - 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. fusonic/linq

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

fusonic/linq
============

LINQ 2 objects class for PHP

v2.0.4(8y ago)74312.7k—8.1%10[4 issues](https://github.com/fusonic/linq/issues)3MITPHPPHP &gt;=5.5.0

Since Jul 22Pushed 3y ago18 watchersCompare

[ Source](https://github.com/fusonic/linq)[ Packagist](https://packagist.org/packages/fusonic/linq)[ Docs](http://fusonic.github.io/fusonic-linq/)[ RSS](/packages/fusonic-linq/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (7)Dependencies (1)Versions (14)Used By (3)

> ## **Project discontinued!**
>
> [](#project-discontinued)
>
> **Development and maintenance of `fusonic/linq` is discontinued since there are more popular options available. We recommend to use `illuminate/collections` ([docs](https://laravel.com/docs/9.x/collections), [GitHub](https://github.com/illuminate/collections)) in new projects. Feel free to use existing versions and/or fork `fusonic/linq` for your own needs.**

fusonic/linq
============

[](#fusoniclinq)

[![Build Status](https://camo.githubusercontent.com/d6c342e3844890af086affdaf3cd275eb81ea300e348dc4c3c58e6183f8e73a9/68747470733a2f2f7472617669732d63692e6f72672f6675736f6e69632f6c696e712e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/fusonic/linq)[![Total Downloads](https://camo.githubusercontent.com/e0f0fff98e1599e56a594a7a466ebf0de3f0ef566b51cec1815af656867fa8f2/68747470733a2f2f706f7365722e707567782e6f72672f6675736f6e69632f6c696e712f646f776e6c6f6164732e706e67)](https://packagist.org/packages/fusonic/linq)

fusonic/linq is a lightweight PHP library inspired by the LINQ 2 Objects extension methods in .NET.

For a full introduction read my blog-post:

LINQ queries offer three main advantages over traditional foreach loops:

- They are more concise and readable, especially when filtering multiple conditions.
- They provide powerful filtering, ordering, and grouping capabilities with a minimum of application code.
- In general, the more complex the operation you want to perform on the data, the more benefit you will realize by using LINQ instead of traditional iteration techniques.

Requirements
------------

[](#requirements)

fusonic/linq is supported on PHP 5.5 and up.

Installation &amp; Usage
------------------------

[](#installation--usage)

The most flexible installation method is using Composer: Simply create a composer.json file in the root of your project:

```
{
    "require": {
        "fusonic/linq": "@dev"
    }
}
```

Install composer and run install command:

```
curl -s http://getcomposer.org/installer | php
php composer.phar install
```

Once installed, include vendor/autoload.php in your script to autoload fusonic/linq.

```
require 'vendor/autoload.php';
use Fusonic\Linq\Linq;

Linq::from([])->count();
```

Examples
--------

[](#examples)

### Calculate the average file size of files in a directory:

[](#calculate-the-average-file-size-of-files-in-a-directory)

```
$source = glob("files/*");
Linq::from($source)
  ->select(function($i) { return filesize($i); })
  ->average();
```

### Find all files bigger than 1024 bytes and return the fileinfo object:

[](#find-all-files-bigger-than-1024-bytes-and-return-the-fileinfo-object)

```
$source = glob("files/*");
Linq::from($source)
  ->where(function($i) { return filesize($i) > 1024; })
  ->select(function($i) { return pathinfo($i); });
```

### Search for all users containing "Max 1", Skip 5 items, Take 2 items and select the property ID of each user:

[](#search-for-all-users-containing-max-1-skip-5-items-take-2-items-and-select-the-property-id-of-each-user)

```
$result = Linq::from($users)
    ->where(function (User $u) { return strstr($u->surname, "Max 1");  })
    ->skip(5)
    ->take(2)
    ->select(function (User $u) { return $u->usrId; });
```

### Flatten multiple sequences into one sequence:

[](#flatten-multiple-sequences-into-one-sequence)

```
$array1 = ["key" => "a", "data" => ["a1", "a2"]];
$array2 = ["key" => "b", "data" => ["b1", "b2"]];
$array3 = ["key" => "c", "data" => ["c1", "c2"]];

$allArrays = [$array1, $array2, $array3];

$result = Linq::from($allArrays)
    ->selectMany(function($x) { return $x["data"]; })
    ->toArray();

// $result is now: ["a1", "a2", "b1", "b2", "c1", "c2"];
```

### Map sequence to array with key/value selectors:

[](#map-sequence-to-array-with-keyvalue-selectors)

```
$category1 = new stdClass(); $category1->key = 1; $category1->value = "Cars";
$category2 = new stdClass(); $category2->key = 2; $category2->value = "Ships";

$result = Linq::from([$category1, $category2])
    ->toArray(
        function($x) { return $x->key; }, // key-selector
        function($x) { return $x->value; } // value-selector
    );

// $result is now: [1 => "Cars", 2 => "Ships"];
```

### The aggregate method makes it simple to perform a calculation over a sequence of values:

[](#the-aggregate-method-makes-it-simple-to-perform-a-calculation-over-a-sequence-of-values)

```
$numbers = Linq::from([1,2,3,4]);
$sum = $numbers->aggregate(function($a, $b) { return $a + $b; });
// echo $sum; // output: 10 (1+2+3+4)

$chars = Linq::from(["a", "b", "c"]);
$csv = $chars->aggregate(function($a, $b) { return $a . "," . $b; });
// echo $csv; // output: "a,b,c"

$chars = Linq::from(["a", "b", "c"]);
$csv = $chars->aggregate(function($a, $b) { return $a . "," . $b; }, "seed");
// echo $csv; // output: "seed,a,b,c"
```

### The chunk method makes it simple to split a sequence into chunks of a given size:

[](#the-chunk-method-makes-it-simple-to-split-a-sequence-into-chunks-of-a-given-size)

```
$chunks = Linq::from(["a","b","c","d","e"])->chunk(2);
$i = 0;
foreach($chunk in $chunks) {
  $i++;
  echo "Row $i ";
  foreach($char in $chunk) {
    echo $char . "|";
  }
}
// Result:
// Row 1
// a|b
// Row 2
// c|d
// Row 3
// e|
```

List of methods provided by fusonic/linq:
-----------------------------------------

[](#list-of-methods-provided-by-fusoniclinq)

```
aggregate($func, $seed = null) // Applies an accumulator function over a sequence.
all($func) // Determines wheter all elements satisfy a condition.
any($func) // Determines wheter any element satisfies a condition.
average($func = null) // Computes the average of all numeric values.
concat($second) // Concatenates 2 sequences
contains($value) // Determines whether a sequence contains a specified element.
count() // Counts the elements of the sequence.
chunk($chunksize) // Splits the sequence in chunks according to $chunksize.
except($second) // Returns all items except the ones of the given sequence.
distinct($func = null) // Returns all distinct items of a sequence using the optional selector.
each($func) // Performs the specified action on each element of the sequence.
elementAt($index) // Returns the element at a specified index or throws an exception.
elementAtOrNull($index) // Returns the element at a specified index or returns null
first($func = null) // Returns the first element that satisfies a specified condition or throws an exception.
firstOrNull($func = null) // Returns the first element, or NULL if the sequence contains no elements.
groupBy($keySelector) // Groups the object according to the $keySelector generated key.
intersect($second) // Intersects the Linq sequence with second Iterable sequence.
last($func = null) // Returns the last element that satisfies a specified condition or throws an exception.
lastOrNull($func = null) // Returns the last element that satisfies a condition or NULL if no such element is found.
max($func = null) //  Returns the maximum item value according to $func.
min($func = null) //  Returns the minimum item value according to $func
orderBy($func) // Sorts the elements in ascending order according to a key provided by $func.
orderByDescending($func) // Sorts the elements in descending order according to a key provided by $func.
select($func) // Projects each element into a new form by invoking the selector function.
selectMany($func) // Projects each element of a sequence to a new Linq and flattens the resulting sequences into one sequence.
single($func = null) // Returns the only element that satisfies a specified condition or throws an exception.
singleOrDefault($func = null) // Returns the only element that satisfies a specified condition or returns Null.
skip($count) // Bypasses a specified number of elements and then returns the remaining elements.
sum($func = null) // Gets the sum of all items or by invoking a transform function on each item to get a numeric value.
take($count) // Returns a specified number of contiguous elements from the start of a sequence.
toArray($keySelector=null, $valueSelector=null) // Creates an Array from this Linq object with an optional key selector.
where($func) // Filters the Linq object according to func return result.
```

Simple, Consistent and Predictable
----------------------------------

[](#simple-consistent-and-predictable)

One important design goal was the principle of the least surprise. As PHP is a fully dynamic language with nearly no type-safety, it is common to shoot yourself into the foot because of accidentally mixing up incompatible types.

We protect you from these programing errors by asserting that every callback functions you supply to the library must return a correctly typed value. In addition, every supported aggregate function will throw an exception if you are accidentally mixing up incompatible types.

This means that we made this library totally predictable in what it does, and verified that every function has its defined exceptions which are thrown when certain operations fail, or if certain types are not correct.

```
/* Throws an UnexpectedValueException if the
provided callback function does not return a boolean */
Linq::from(["1", "1"])
->where(function($x) { return "NOT A BOOLEAN"; });

/* Throws an UnexpectedValueException if one of the values
is not convertible to a numeric value:*/
Linq::from([1, 2, "Not a numeric value"])
->sum();
```

Running tests
-------------

[](#running-tests)

```
./vendor/bin/phpunit tests/
```

###  Health Score

43

—

FairBetter than 91% of packages

Maintenance19

Infrequent updates — may be unmaintained

Popularity47

Moderate usage in the ecosystem

Community28

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 57.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 ~194 days

Recently: every ~166 days

Total

7

Last Release

3154d ago

Major Versions

v1.1.0 → v2.0.02015-12-04

PHP version history (2 changes)1.0.0PHP &gt;=5.3.2

v2.0.0PHP &gt;=5.5.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/229567?v=4)[Matthias Burtscher](/maintainers/mburtscher)[@mburtscher](https://github.com/mburtscher)

![](https://avatars.githubusercontent.com/u/338856?v=4)[David Roth](/maintainers/davidroth)[@davidroth](https://github.com/davidroth)

![](https://avatars.githubusercontent.com/u/3588470?v=4)[Arjan Frans](/maintainers/arjanfrans)[@arjanfrans](https://github.com/arjanfrans)

![](https://avatars.githubusercontent.com/u/1465587?v=4)[Michael Zangerle](/maintainers/michaelzangerle)[@michaelzangerle](https://github.com/michaelzangerle)

---

Top Contributors

[![davidroth](https://avatars.githubusercontent.com/u/338856?v=4)](https://github.com/davidroth "davidroth (61 commits)")[![rponudic](https://avatars.githubusercontent.com/u/811499?v=4)](https://github.com/rponudic "rponudic (20 commits)")[![mburtscher](https://avatars.githubusercontent.com/u/229567?v=4)](https://github.com/mburtscher "mburtscher (14 commits)")[![robations](https://avatars.githubusercontent.com/u/205320?v=4)](https://github.com/robations "robations (8 commits)")[![voorproever](https://avatars.githubusercontent.com/u/19673115?v=4)](https://github.com/voorproever "voorproever (3 commits)")

---

Tags

linqlinq2objects

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/fusonic-linq/health.svg)

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

###  Alternatives

[athari/yalinqo

YaLinqo, a LINQ-to-objects library for PHP

4561.2M5](/packages/athari-yalinqo)[ginq/ginq

LINQ to Object inspired DSL for PHP

192257.5k3](/packages/ginq-ginq)[helori/laravel-seo

SEO tools to insert meta and structured-data in laravel projects

134.9k](/packages/helori-laravel-seo)

PHPackages © 2026

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