Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

223 lines (144 sloc) 3.475 kb

PHP Collections

A simple chainable wrapper around common array functions, map, filter, reduce etc...

$set = Collection::fromArray(array(1,2,3,4));

$tmp = $set->filter(function($val){
    return $val % 2 == 0;
})->map(function($val){
    return $val * 2;
})->reduce(function($sum,$val){
    return $sum + $val;
});

echo $tmp /* 12 */

Documentation


fromArray($array) - static

Create a new collection from an array.

Arguments

  • array - The array to use.

Example

$set = Collection::fromArray(1,2,3,4);

map($fn)

Apply a function to each element replacing the old values with the ones returned.

Arguments

  • fn($value) - The function to apply.

Example

$set->map(function($val){
    return $val * 2;
});

filter($fn)

Remove elements which do not pass the filter.

Arguments

  • fn($value) - The test function, should return true or false.

Example

$set->filter(function($val){
    return $val % 2 == 0;
});

reduce($fn,$mem)

Reduce the elements to a single value.

NB: Reduce returns the result of the reduction NOT a collection.

Arguments

  • fn($mem,$val) - The reduction function
  • $mem - The initial state of the reduction

Example

$set->reduce(function($sum,$value){
    return $sum + $value;
},0);

withEach($fn)

Call a function with each element in the collection.

Arguments

  • fn($val) - The function.

Example

$set->withEach(function($val){
    echo $val;
});

start($fn)

Apply a function to the first element replacing the element with the return value.

Arguments

  • fn($val) - The function.

Example

$set->start(function($val){
    return "Start: " . $val;
});

end($fn)

Apply a function to the last element replacing the element with the return value.

Arguments

  • fn($val) - The function.

Example

$set->end(function($val){
    return $val . " End";
});

sort($fn)

Sort the contents of a collection using a callback function.

Arguments

  • fn($a,$b) - The function.

Example

$set->sort(function($a,$b){
    return $a - $b;
});

count()

Return the number of element in the collection.

Example

$set->count();

value()

Return the underlying array.

Example

$set->value();

isEmpty()

Return true if there are no elements in the collection.

Example

$set->isEmpty();


Jump to Line
Something went wrong with that request. Please try again.