Collections

Introduction

The Kiaan\Data\Collection class provides a fluent, convenient wrapper for working with arrays of data.

$collection = Collection::collect([1, 2, 3]);

$collection = collect([1, 2, 3]);

Extending Collections

Collections are "xCommand", which allows you to add additional methods to the Collection class at run time.

use Kiaan\Collection;
use Kiaan\Str;

Collection::xCommand('toUpper', function(){
  return Collection::map(function ($value) {
      return Str::upper($value);
  });
});

collect(["hassan", "ahmed"])->toUpper();

// ['HASSAN', 'AHMED']

Method Listing

all()

The all method returns the underlying array represented by the collection:

collect([1, 2, 3])->all();
 
// [1, 2, 3]

add()

Add an element onto the end of the map without returning a new map.

collect(['a', 'b'])->add(['c']);

// Or
collect(['a', 'b'])->add('c');

// ['a', 'b', 'c']

get()

Gets a value in an array by dot notation for the keys.

$array = [
     'foo' => 'bar',
     'baz' => [
         'qux' => 'foobar'
     ]
];

collect($array)->get("baz.qux");
collect($array)->get("bazr.quxr", 'default');
collect($array)->get("baz.qux", function () { return 'email@example.com'; });

set()

Set a value in an array by dot notation for the keys.

$array = [
     'foo' => 'bar',
     'baz' => [
         'qux' => 'foobar'
     ]
];

collect($array)->set('baz.qux', 'value');

chunk()

Chunk the underlying collection array.

 collect([1, 2, 3, 4, 5, 6, 7])->chunk(4);

collapse()

Collapse the collection of items into a single array.

collect([[1, 2, 3],[4, 5, 6],[7, 8, 9]])->collapse();

combine()

Create a collection by using this collection for keys and another for its values.

collect(['name', 'job'])->combine(['Hassan', 'programmer'])

crossJoin()

Cross join with the given lists, returning all possible permutations.

collect([1, 2])->crossJoin(['a', 'b']);

/*
    [
        [1, 'a'],
        [1, 'b'],
        [2, 'a'],
        [2, 'b'],
    ]
*/

diff()

Get the items in the collection that are not present in the given items.

collect([1, 2, 3, 4, 5])->diff([2, 4, 6, 8]);

collect(['color' => 'orange', 'type' => 'fruit', 'remain' => 6])->diff(['color' => 'yellow', 'type' => 'fruit', 'remain' => 3, 'used' => 6])

diffKeys()

Get the items in the collection whose keys are not present in the given items.

collect(['one' => 10, 'two' => 20, 'three' => 30, 'four' => 40, 'five' => 50])->diffKeys(['two' => 2, 'four' => 4, 'six' => 6, 'eight' => 8]);

duplicates()

Get the items in the collection whose keys are not present in the given items.

collect(['a', 'b', 'a', 'c', 'b'])->duplicates();

collect([ ['email' => 'mohammed@example.com', 'position' => 'Developer'], ['email' => 'hassan@example.com', 'position' => 'Designer'], ['email' => 'ali@example.com', 'position' => 'Developer'], ])->duplicates('position');

each()

Execute a callback over each item.

collect([1, 2])->each(function ($item, $key) { // code });

nth()

Create a new collection consisting of every n-th element.

collect(['a', 'b', 'c', 'd', 'e', 'f'])->nth(4);

collect(['a', 'b', 'c', 'd', 'e', 'f'])->nth(4,1);

except()

Get all items except for those with the specified keys.

collect(['ID' => 1, 'Name' => "Hassan", 'Country' => "Egypt"])->except(['ID', 'Country']);

filter()

Run a filter over each of the items.

collect([1, 2, 3, 4])->filter(function ($value) { return $value < 3; });

first()

Get the first item from the collection.

collect([1, 2, 3, 4])->first();

collect([1, 2, 3, 4])->first(function ($value, $key) { return $value > 2; });

flatten()

Get a flattened array of the items in the collection.

collect(['name'=>'Hassan','languages'=>['php', 'javascript']])->flatten();

collect([1,2,3])->flatten();

flatten()

Get a flattened array of the items in the collection.

collect(['name'=>'Hassan','languages'=>['php', 'javascript']])->flatten();
collect([1,2,3])->flatten();

flip()

Flip the items in the collection.

collect(['Name' => 'Hassan', 'Framework' => 'Kiaan'])->flip();

collect(['a','b','c'])->flip();

forget()

Remove an item from the collection by key.

collect(['a','b','c'])->forget(0);

collect(['ID' => 1, 'Name' => "Hassan", 'Country' => "Egypt"])->forget(['ID', 'Country']);

paginate()

"Paginate" the collection by slicing it into a smaller collection.

collect([1, 2, 3, 4, 5, 6, 7, 8, 9])->paginate(2, 3);

groupBy()

Function that groups an array of associative arrays by some key.

collect([ ['id' => '10', 'product' => 'pc'], ['id' => '10', 'product' => 'mobile'], ['id' => '11', 'product' => 'laptop'], ])->groupBy('id');

intersect()

Intersect the collection with the given items.

collect(['mobile', 'pc', 'laptop'])->intersect(['tv', 'pc', 'laptop']);

intersectByKeys()

Intersect the collection with the given items by key.

collect(['serial' => 'HS321', 'type' => 'tv', 'year' => 2020])->intersectByKeys(['reference' => 'HS123', 'type' => 'mobile', 'year' => 2021]);

keys()

Get the keys of the collection items.

collect(["name"=>"hassan", "country"=>"egypt"])->keys();

last()

Get the first item from the collection.

collect([1, 2, 3, 4])->last();

collect([1, 2, 3, 4])->last(function ($value, $key) { return $value < 3; });

map()

Run a map over each of the items.

collect([1, 2, 3, 4])->map(function ($item, $key) { return $item * 2; });

mapWithKeys()

Run an associative map over each of the items.

collect([ [ 'name' => 'hassan', 'department' => 'Sales', 'email' => 'hassan@example.com', ], [ 'name' => 'ahmed', 'department' => 'Marketing', 'email' => 'ahmed@example.com', ] ])->mapWithKeys(function ($item) { return [$item['email'] => $item['name']]; });

merge()

Run an associative map over each of the items.

collect(['product_id' => 1, 'price' => 100])->merge(['price' => 200, 'discount' => false]);

collect(['Desk', 'Chair'])->merge(['Bookcase', 'Door']);

mergeRecursive()

Recursively merge the collection with the given items.

collect(['product_id' => 1, 'price' => 100])->mergeRecursive([ 'product_id' => 2, 'price' => 200, 'discount' => false ]);

only()

Get the items with the specified keys.

collect([ 'product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false ])->only(['product_id', 'name']);

pad()

Pad collection to the specified length with a value.

collect(['A', 'B', 'C'])->pad(5, 0);

collect(['A', 'B', 'C'])->pad(-5, 0);

prepend()

Push an item onto the beginning of the collection.

collect([1, 2, 3, 4, 5])->prepend(0);

collect([1, 2, 3, 4, 5])->prepend(0, 'zero');

push()

Push one or more items onto the end of the collection.

collect([1, 2, 3, 4])->push(5);

put()

Put an item in the collection by key.

collect([1, 2, 3, 4])->put(3, 5);

random()

Get one or a specified number of items randomly from the collection.

Collection::collect([1, 2, 3, 4, 5])->random();

Collection::collect([1, 2, 3, 4, 5])->random(3);

reduce()

Reduce the collection to a single value.

collect([1, 2, 3])->reduce(function ($carry, $item) { return $carry + $item; });

collect([1, 2, 3])->reduce(function ($carry, $item) { return $carry + $item; }, 4);

reject()

Create a collection of all elements that do not pass a given truth test.

collect([1, 2, 3, 4])->reject(function ($value) { return $value > 2; });

replace()

Replace the collection items with the given items.

collect(['Hassan', 'Mohammed', 'Ahmed'])->replace([1 => 'Ali', 3 => 'Taha']);

replaceRecursive()

Recursively replace the collection items with the given items.

collect(['Hassan','Ahmed',['Ali','Mohhamed','Ibrahim']])->replaceRecursive([ 'Salah', 2 => [1 => 'Yasmin'] ]);

reverse()

Reverse items order.

collect(['a', 'b', 'c', 'd', 'e'])->reverse();

shift()

Get and remove the first item from the collection.

collect(['a', 'b', 'c', 'd', 'e'])->shift();

shuffle()

Shuffle the items in the collection.

collect([1, 2, 3, 4, 5])->shuffle();

skip()

Skip the first {$count} items.

collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])->skip(5);

slice()

Slice the underlying collection array.

collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])->slice(4);

collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])->slice(4, 2);

sort()

Sort through each item with a callback.

collect([5, 3, 1, 2, 4])->sort();

collect([2, 1, 3])->sort(function ($x, $y){ return $x < $y ? -1 : 1; });  

sortDesc()

Sort items in descending order.

collect([5, 3, 1, 2, 4])->sortDesc();

sortKeys()

Sort the collection keys.

collect([ 'id' => 123, 'first' => 'Hassan', 'last' => 'Kerdash'])->sortKeys();

sortKeysDesc()

Sort the collection keys in descending order.

collect([ 'id' => 123, 'first' => 'Hassan', 'last' => 'Kerdash'])->sortKeysDesc();

splice()

Splice a portion of the underlying collection array.

collect([1, 2, 3, 4, 5])->splice(2);

collect([1, 2, 3, 4, 5])->splice(2, 1);

collect([1, 2, 3, 4, 5])->splice(2, 1, [10, 11]);

split()

Split a collection into a certain number of groups.

collect([1, 2, 3, 4, 5])->split(3);

splitIn()

Split a collection into a certain number of groups, and fill the first groups completely.

collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])->splitIn(3);

take()

Take the first or last {$limit} items.

collect([0, 1, 2, 3, 4, 5])->take(3);

collect([0, 1, 2, 3, 4, 5])->take(-2);

transform()

Transform each item in the collection using a callback.

collect([1, 2, 3, 4, 5])->transform(function ($item, $key) { return $item * 2; });

union()

Union the collection with the given items.

collect([1 => ['a'], 2 => ['b']])->union([3 => ['c'], 1 => ['b']]);

unique

Return only unique items from the collection array.

collect(["name"] => ["Hassan", "Ali", "Hassan", "Ahmed"])->unique("name");

collect([ ["id"=>1, "value"=>1], ["id"=>2, "value"=>2], ["id"=>3, "value"=>1], ])->unique("value");

where()

Filter items by the given key value pair.

collect([ ['product' => 'Pc', 'price' => 200], ['product' => 'Phone', 'price' => 100], ['product' => 'Mobile', 'price' => 150], ['product' => 'Laptop', 'price' => 100], ])->where('price', 100);

collect([ ['product' => 'Pc', 'price' => 200], ['product' => 'Phone', 'price' => 100], ['product' => 'Mobile', 'price' => 150], ['product' => 'Laptop', 'price' => 100], ])->where('price', '=' ,100);

whereStrict()

Filter items by the given key value pair using strict comparison.

collect([ ['product' => 'Pc', 'price' => 200], ['product' => 'Phone', 'price' => 100], ['product' => 'Mobile', 'price' => 150], ['product' => 'Laptop', 'price' => 100], ])->whereStrict('price', 100);

whereBetween()

Filter items such that the value of the given key is between the given values.

collect([ ['product' => 'TV', 'price' => 200], ['product' => 'Laptop', 'price' => 80], ['product' => 'Speaker', 'price' => 150], ['product' => 'Mobile', 'price' => 30], ['product' => 'PC', 'price' => 100], ])->whereBetween('price', [100, 200]);

whereIn()

Filter items by the given key value pair.

collect([ ['product' => 'PC', 'price' => 200], ['product' => 'Mobile', 'price' => 100], ['product' => 'Phone', 'price' => 150], ['product' => 'TV', 'price' => 100], ])->whereIn('price', [150, 200]);

whereInStrict()

Filter items by the given key value pair using strict comparison.

collect([ ['product' => 'PC', 'price' => 200], ['product' => 'Mobile', 'price' => 100], ['product' => 'Phone', 'price' => 150], ['product' => 'TV', 'price' => 100], ])->whereInStrict('price', [150, 200]);

whereInstanceOf()

Filter the items, removing any items that don't match the given type.

collect([ new User, new User, new Admin, ])->whereInstanceOf(User::class)

whereNotBetween()

Filter items such that the value of the given key is not between the given values.

collect([ ['product' => 'TV', 'price' => 200], ['product' => 'Laptop', 'price' => 80], ['product' => 'Speaker', 'price' => 150], ['product' => 'Mobile', 'price' => 30], ['product' => 'PC', 'price' => 100], ])->whereNotBetween('price', [100, 200]);

whereNotIn()

Filter items by the given key value pair.

collect([ ['product' => 'PC', 'price' => 200], ['product' => 'Mobile', 'price' => 100], ['product' => 'Phone', 'price' => 150], ['product' => 'TV', 'price' => 100], ])->whereNotIn('price', [150, 200]);

whereNotInStrict()

Filter items by the given key value pair using strict comparison.

collect([ ['product' => 'PC', 'price' => 200], ['product' => 'Mobile', 'price' => 100], ['product' => 'Phone', 'price' => 150], ['product' => 'TV', 'price' => 100], ])->whereNotInStrict('price', [150, 200]);

whereNotNull()

Filter items where the value for the given key is not null.

collect([ ['name' => 'pc'], ['name' => null], ['name' => 'phone'], ])->whereNotNull('name');

whereNull()

Filter items where the value for the given key is null.

collect([ ['name' => 'pc'], ['name' => null], ['name' => 'phone'], ])->whereNull('name');

zip()

Zip the collection together with one or more arrays.

collect(['Phone', 'PC'])->zip([100, 200]);

when()

Apply the callback if the value is truthy.

collect([1,2,3])->when(true, function ($map) {return $map->push(4);});

whenEmpty()

Apply the callback if the collection is empty.

collect([])->whenEmpty(function ($map) { return $map->push('Hassan'); });

whenNotEmpty()

Apply the callback if the collection is not empty.

collect(['Ahmed', 'Mohammed'])->whenNotEmpty(function ($map) { return $map->push('Hassan'); });

toArray()

Returns a plain array of the given elements.

collect(['Ahmed', 'Mohammed'])->toArray();

toObject()

Returns a object of the given elements.

collect(['Ahmed', 'Mohammed'])->toObject();

toJson()

Returns a json of the given elements.

collect(['Ahmed', 'Mohammed'])->toJson();

avg()

Get the average value of a given key.

collect([1, 1, 2, 4])->avg();

collect([['price' => 10],['price' => 10],['price' => 20],['price' => 40]])->avg("price");

contains()

Determine if an item (value) exists in the collection.

collect([1, 2, 3, 4, 5])->contains(1);

collect(['Name'=>"Hassan", 'Country'=>"Egypt"])->contains("Egypt");

count()

Count the number of items in the collection.

collect([1, 2, 3, 4, 5])->count();

collect(['Name'=>"Hassan", 'Country'=>"Egypt"])->count();

countBy()

Count the number of items in the collection by a field.

collect([1, 2, 3, 3])->countBy(3);

every()

Determine if all items pass the given truth test.

collect([1, 2, 3, 4])->every(function ($value, $key) { return $value > 2; });

query()

Convert the array into a query string.

collect(['id'=>1, "page"=>2])->query();

has()

Determine if an item exists in the collection by key.

collect(["name"=>"hassan", "country"=>"egypt"])->has("name", "country");

collect(["name"=>"hassan", "country"=>"egypt"])->has(["name", "age"]);

collect(["name"=>"hassan", "country"=>"egypt"])->has("country");

implode()

Concatenate values of a given key as a string.

collect([1,2,3])->implode();

collect([1,2,3])->implode("-");

collect(["name"=>"hassan", "country"=>"egypt"])->implode("-");

isEmpty()

Determine if the collection is empty or not.

collect([])->isEmpty();

isNotEmpty()

Determine if the collection is not empty.

collect([])->isNotEmpty();

max()

Get the max value of a given key.

collect([1, 2, 3, 4, 5])->max();

collect([ ['foo' => 10], ['foo' => 20] ])->max();

collect([ ['foo' => 10], ['foo' => 20], ['boo' => 30], ['boo' => 40] ])->max("boo");

min()

Get the min value of a given key.

collect([1, 2, 3, 4, 5])->min();

collect([ ['foo' => 10], ['foo' => 20] ])->min();

collect([ ['foo' => 10], ['foo' => 20], ['boo' => 30], ['boo' => 40] ])->min("boo");

pipe()

Pass the collection to the given callback and return the result.

collect([1, 2, 3])->pipe(function ($map) { return $Collection::all(); });

pop()

Get and remove the last item from the collection.

collect([1, 2, 3, 4, 5])->pop();

Search the collection for a given value and return the corresponding key if successful.

collect([2, 4, 6, 8])->search(8);

collect([2, 4, 6, 8])->search(4, $strict = true);

collect([2, 4, 6, 8])->search(function ($item, $key) { return $item > 5; });

sum()

Get the sum of the given values.

collect([1, 2, 3, 4, 5])->sum();

collect([ ['name' => 'tv', 'price' => 1], ['name' => 'phone', 'price' => 2], ])->sum();

range()

Create a collection with the given range.

Collection::range(1, 10);

column()

Returns the values from a single column.

collect([ ['name' => 'tv', 'price' => 1], ['name' => 'phone', 'price' => 2], ])->column('name');

resource()

Returns a new object created from the resource.

$array = array(
  [
    "name" => "Hassan",
    "lastname" => "Kerdash",
    "age" => 24,
   ],
   [
     "name" => "Ali",
     "lastname" => "Mohammed",
     "age" => 25,
   ]
);

$data = collect($array)->resource(function($item){ 
  return [
    "name" => $item->name.' '.$item->lastname,
    "age" => $item->age,
  ];
});

Last updated