class Bag implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable (View source)

An OO implementation of PHP's array functionality and more (minus mutability).

All methods that allow mutation are deprecated, use MutableBag for those use cases instead.

Properties

protected array $items

Methods

__construct(array $items = [])

Constructor.

static Bag
of()

Creates a list from the arguments given.

static Bag
from(iterable|stdClass|null $collection)

Create a bag from a variety of collections.

static Bag
fromRecursive(iterable|stdClass|null $collection)

Takes the items and recursively converts them to Bags.

static Bag
combine(iterable $keys, iterable $values)

Creates a bag by using one collection for keys and another for its values.

array
toArray()

Returns the array of items.

array
toArrayRecursive()

Returns the items recursively converting them to arrays.

Bag
createFrom(array $items)

Creates a new instance from the specified items.

bool
has(string $key)

Returns whether an item exists for the given key.

bool
hasPath(string $path)

Returns whether a key exists using path syntax to check nested data.

bool
hasItem(mixed $item)

Returns whether the item is in the bag.

mixed
get(string $key, mixed $default = null)

Returns an item by its key.

mixed
getPath(string $path, mixed $default = null)

Returns an item using path syntax to retrieve nested data.

int
count()

Returns the number of items in this bag.

bool
isEmpty()

Checks whether the bag is empty.

mixed|null
first()

Returns the first item in the list or null if empty.

mixed|null
last()

Returns the last item in the list or null if empty.

string
join(string $separator)

Joins the list to a string.

number
sum()

Returns the sum of the values in this list.

number
product()

Returns the product of the values in this list.

bool
isAssociative()

Returns whether the items in this bag are key/value pairs.

bool
isIndexed()

Returns whether the items in this bag are zero indexed and sequential.

int|string|null
indexOf(mixed $item, int $fromIndex)

Gets the first index/key of a given item.

int|string|null
lastIndexOf(mixed $item, int $fromIndex = null)

Gets the last index/key of a given item.

mixed|null
find(callable $predicate, int $fromIndex)

Returns the first item that matches the $predicate or null.

mixed|null
findLast(callable $predicate, int $fromIndex = null)

Returns the last item that matches the $predicate or null.

mixed|null
findKey(callable $predicate, int $fromIndex)

Returns the first key that matches the $predicate or null.

mixed|null
findLastKey(callable $predicate, int $fromIndex = null)

Returns the last key that matches the $predicate or null.

mixed
randomValue()

Returns a random value.

mixed
randomKey()

Returns a random key.

Bag
call(callable $callable, array $args = null)

Calls the $callable to modify the items.

mutable()

Returns a mutable bag with the items from this bag.

Bag
immutable()

Returns an immutable bag with the items from this bag.

Bag
keys()

Returns a bag with all the keys of the items.

Bag
values()

Returns a bag with all the values of the items.

Bag
map(callable $callback)

Applies the $callable to each value in the bag and returns a new bag with the items returned by the function.

Bag
mapKeys(callable $callback)

Applies the given function to each key in the bag and returns a new bag with the keys returned by the function and their values.

Bag
filter(callable $predicate)

Returns a bag with the items that satisfy the $predicate.

Bag
reject(callable $predicate)

Returns a bag with the items that do not satisfy the $predicate. The opposite of filter.

Bag
clean()

Returns a bag with falsely values filtered out.

Bag
replace(iterable $collection)

Replaces items in this bag from the $collection by comparing keys and returns the result.

Bag
replaceRecursive(iterable $collection)

Returns a bag with the items replaced recursively from the $collection.

Bag
defaults(iterable $collection)

Returns a bag with the items from the $collection added to the items in this bag if they do not already exist by comparing keys. The opposite of replace.

Bag
defaultsRecursive(iterable $collection)

Returns a bag with the items from the $collection recursively added to the items in this bag if they do not already exist by comparing keys. The opposite of replaceRecursive.

Bag
merge(iterable $list)

Returns a bag with the items merged with the given list.

Bag
slice(int $offset, int|null $length = null, bool $preserveKeys = false)

Returns a bag with a slice of $length items starting at position $offset extracted from this bag.

Bag[]
partition(callable $predicate)

Partitions the items into two bags according to the $predicate.

Bag
column(string|int|null $columnKey, string|int|null $indexKey = null)

Returns a bag with the values from a single column, identified by the $columnKey.

Bag
flip()

Returns a bag with all keys exchanged with their associated values.

mixed
reduce(callable $callback, mixed $initial = null)

Iteratively reduce the items to a single value using the $callback function.

Bag
unique()

Returns a bag with duplicate values removed.

Bag|Bag[]
chunk(int $size, bool $preserveKeys = false)

Returns a bag with the items split into chunks.

Bag
pad(int $size, mixed $value)

Returns a bag with the items padded to the $size with the $value.

Bag
countValues()

Returns a bag with values mapped to the number of times they are in the bag.

Bag
flatten(int $depth = 1)

Returns a bag with the items flattened.

Bag
randomValues(int $size)

Returns a bag with a random number of key/value pairs.

Bag
randomKeys(int $size)

Returns a list with a random number of keys (as values).

Bag
pick(iterable|string|string[]|int|int[] $keys)

Returns a bag with only $keys.

Bag
omit(iterable|string|string[]|int|int[] $keys)

Returns a bag without $keys.

Bag
diff(iterable $collection, callable $comparator = null)

Returns a bag without the values that are also in $collection.

Bag
diffBy(iterable $collection, callable $iteratee)

Returns a bag without the values that are also in $collection based on the $iteratee function.

Bag
diffKeys(iterable $collection, callable $comparator = null)

Returns a bag without the keys that are also in $collection.

Bag
diffKeysBy(iterable $collection, callable $iteratee)

Returns a bag without the keys that are also in $collection based on the $iteratee function.

Bag
intersect(iterable $collection, callable $comparator = null)

Returns a bag with only the values that are also in $collection.

Bag
intersectBy(iterable $collection, callable $iteratee)

Returns a bag with only the values that are also in $collection based on the $iteratee function.

Bag
intersectKeys(iterable $collection, callable $comparator = null)

Returns a bag with only the keys that are also in $collection.

Bag
intersectKeysBy(iterable $collection, callable $iteratee)

Returns a bag with only the keys that are also in $collection based on the $iteratee function.

Bag
sort(int $order = SORT_ASC, int $flags = SORT_REGULAR, bool $preserveKeys = false)

Returns a bag with the values sorted.

Bag
sortBy(callable $iteratee, int $order = SORT_ASC, bool $preserveKeys = false)

Returns a bag with the values sorted based on the $iteratee function.

Bag
sortWith(callable $comparator, bool $preserveKeys = false)

Returns a bag with the values sorted with the $comparator.

Bag
sortKeys(int $order = SORT_ASC, int $flags = SORT_REGULAR)

Returns a bag with the keys sorted.

Bag
sortKeysBy(callable $iteratee, int $order = SORT_ASC)

Returns a bag with the keys sorted based on the $iteratee function.

Bag
sortKeysWith(callable $comparator)

Returns a bag with the keys sorted with the $comparator.

Bag
reverse(bool $preserveKeys = false)

Returns a bag with the items reversed.

Bag
shuffle()

Returns a bag with the items shuffled.

add(mixed $item) deprecated

Adds an item to the end of this bag.

prepend(mixed $item) deprecated

Adds an item to the beginning of this bag.

set(string $key, mixed $value) deprecated

Sets a item by key.

setPath(string $path, mixed $value) deprecated

Sets a value using path syntax to set nested data.

clear() deprecated

Remove all items from bag.

mixed
remove(string|int $key, mixed|null $default = null) deprecated

Removes and returns the item at the specified $key from the bag.

removeItem(mixed $item) deprecated

Removes the given item from the bag if it is found.

mixed|null
removeFirst() deprecated

Removes and returns the first item in the list.

mixed|null
removeLast() deprecated

Removes and returns the last item in the list.

Details

__construct(array $items = [])

Constructor.

Parameters

array $items

static Bag of()

Creates a list from the arguments given.

Return Value

Bag

static Bag from(iterable|stdClass|null $collection)

Create a bag from a variety of collections.

Parameters

iterable|stdClass|null $collection

Return Value

Bag

static Bag fromRecursive(iterable|stdClass|null $collection)

Takes the items and recursively converts them to Bags.

Parameters

iterable|stdClass|null $collection

Return Value

Bag

static Bag combine(iterable $keys, iterable $values)

Creates a bag by using one collection for keys and another for its values.

Parameters

iterable $keys
iterable $values

Return Value

Bag

array toArray()

Returns the array of items.

Return Value

array

array toArrayRecursive()

Returns the items recursively converting them to arrays.

Return Value

array

protected Bag createFrom(array $items)

Creates a new instance from the specified items.

This method is provided for derived classes to specify how a new instance should be created when constructor semantics have changed.

Parameters

array $items

Return Value

Bag

bool has(string $key)

Returns whether an item exists for the given key.

Parameters

string $key The key

Return Value

bool

bool hasPath(string $path)

Returns whether a key exists using path syntax to check nested data.

Example:

$bag->hasPath('foo/bar/baz')
// => true

This method does not allow for keys that contain /.

Parameters

string $path The path to traverse and check keys from

Return Value

bool

bool hasItem(mixed $item)

Returns whether the item is in the bag.

This uses a strict check so types must much and objects must be the same instance to match.

Parameters

mixed $item

Return Value

bool

mixed get(string $key, mixed $default = null)

Returns an item by its key.

Parameters

string $key The key
mixed $default The default value if the key does not exist

Return Value

mixed

mixed getPath(string $path, mixed $default = null)

Returns an item using path syntax to retrieve nested data.

Example:

// Get the bar key of a set of nested arrays.
// This is equivalent to $data['foo']['baz']['bar'] but won't
// throw warnings for missing keys.
$bag->getPath('foo/bar/baz');

This method does not allow for keys that contain /.

Parameters

string $path The path to traverse and retrieve an item from
mixed $default The default value if the key does not exist

Return Value

mixed

int count()

Returns the number of items in this bag.

Return Value

int

bool isEmpty()

Checks whether the bag is empty.

Return Value

bool

mixed|null first()

Returns the first item in the list or null if empty.

Return Value

mixed|null

mixed|null last()

Returns the last item in the list or null if empty.

Return Value

mixed|null

string join(string $separator)

Joins the list to a string.

Parameters

string $separator The term to join on

Return Value

string A string representation of all the items with the separator between them

number sum()

Returns the sum of the values in this list.

Return Value

number

number product()

Returns the product of the values in this list.

Return Value

number

bool isAssociative()

Returns whether the items in this bag are key/value pairs.

Note: Empty bags are not.

Return Value

bool

bool isIndexed()

Returns whether the items in this bag are zero indexed and sequential.

Note: Empty bags are.

Return Value

bool

int|string|null indexOf(mixed $item, int $fromIndex)

Gets the first index/key of a given item.

This uses a strict check so types must much and objects must be the same instance to match.

Parameters

mixed $item The item to search for
int $fromIndex The starting index to search from. Can be negative to start from that far from the end of the array. If index is out of bounds, it will be moved to first/last index.

Return Value

int|string|null The index or key of the item or null if the item was not found

int|string|null lastIndexOf(mixed $item, int $fromIndex = null)

Gets the last index/key of a given item.

This uses a strict check so types must much and objects must be the same instance to match.

Parameters

mixed $item The item to search for
int $fromIndex The starting index to search from. Default is the last index. Can be negative to start from that far from the end of the array. If index is out of bounds, it will be moved to first/last index.

Return Value

int|string|null The index or key of the item or null if the item was not found

mixed|null find(callable $predicate, int $fromIndex)

Returns the first item that matches the $predicate or null.

Parameters

callable $predicate Function is passed ($value, $key)
int $fromIndex The starting index to search from. Can be negative to start from that far from the end of the array. If index is out of bounds, it will be moved to first/last index.

Return Value

mixed|null

mixed|null findLast(callable $predicate, int $fromIndex = null)

Returns the last item that matches the $predicate or null.

Parameters

callable $predicate Function is passed ($value, $key)
int $fromIndex The starting index to search from. Can be negative to start from that far from the end of the array. If index is out of bounds, it will be moved to first/last index.

Return Value

mixed|null

mixed|null findKey(callable $predicate, int $fromIndex)

Returns the first key that matches the $predicate or null.

Parameters

callable $predicate Function is passed ($value, $key)
int $fromIndex The starting index to search from. Can be negative to start from that far from the end of the array. If index is out of bounds, it will be moved to first/last index.

Return Value

mixed|null

mixed|null findLastKey(callable $predicate, int $fromIndex = null)

Returns the last key that matches the $predicate or null.

Parameters

callable $predicate Function is passed ($value, $key)
int $fromIndex The starting index to search from. Can be negative to start from that far from the end of the array. If index is out of bounds, it will be moved to first/last index.

Return Value

mixed|null

mixed randomValue()

Returns a random value.

Return Value

mixed

Exceptions

InvalidArgumentException when the bag is empty

mixed randomKey()

Returns a random key.

Return Value

mixed

Exceptions

InvalidArgumentException when the bag is empty

Bag call(callable $callable, array $args = null)

Calls the $callable to modify the items.

This allows for chain-ability with custom functionality.

The $callable is given the bag's items (array) as the first parameter and should return an iterable which is then converted to a bag. Any extra parameters passed in to this method are passed to the $callable after the items parameter.


Example with closure:

Bag::from(['red', 'blue'])
    ->call(function (array $colors) {
        $colors[] = 'green';

        return $colors;
    })
    ->join(', ');
// => "red, blue, green"


Example with function name and args:

Bag::from(['red', 'blue'])
    ->call('array_pad', 4, ''); // Assuming bag doesn't have a pad method ;)
// => Bag of ['red', 'blue', '', '']

Parameters

callable $callable Function is given ($items, ...$args) and should return an iterable
array $args Extra parameters to pass to the $callable after the items parameter

Return Value

Bag

MutableBag mutable()

Returns a mutable bag with the items from this bag.

Return Value

MutableBag

Bag immutable()

Returns an immutable bag with the items from this bag.

Return Value

Bag

Bag keys()

Returns a bag with all the keys of the items.

Return Value

Bag

Bag values()

Returns a bag with all the values of the items.

Useful for reindexing a list.

Return Value

Bag

Bag map(callable $callback)

Applies the $callable to each value in the bag and returns a new bag with the items returned by the function.

Note: This differs from array_map in that the callback is passed $key first, then $value.

Parameters

callable $callback Function is passed ($key, $value)

Return Value

Bag

Bag mapKeys(callable $callback)

Applies the given function to each key in the bag and returns a new bag with the keys returned by the function and their values.

Parameters

callable $callback Function is passed ($key, $value)

Return Value

Bag

Bag filter(callable $predicate)

Returns a bag with the items that satisfy the $predicate.

Keys are preserved, so lists could need to be re-indexed.

Note: This differs from array_filter in that the $predicate is passed $key first, then $value.

Parameters

callable $predicate Function is passed ($key, $value)

Return Value

Bag

Bag reject(callable $predicate)

Returns a bag with the items that do not satisfy the $predicate. The opposite of filter.

Keys are preserved, so lists could need to be re-indexed.

Parameters

callable $predicate Function is passed ($key, $value)

Return Value

Bag

Bag clean()

Returns a bag with falsely values filtered out.

Return Value

Bag

Bag replace(iterable $collection)

Replaces items in this bag from the $collection by comparing keys and returns the result.

Parameters

iterable $collection The collection from which items will be extracted

Return Value

Bag

Bag replaceRecursive(iterable $collection)

Returns a bag with the items replaced recursively from the $collection.

This differs from array_replace_recursive in a couple ways:

  • Lists (zero indexed and sequential items) from given collection completely replace lists in this Bag.

  • Null values from given collection do not replace lists or associative arrays in this Bag (they do still replace scalar values).

Parameters

iterable $collection The collection from which items will be extracted

Return Value

Bag

Bag defaults(iterable $collection)

Returns a bag with the items from the $collection added to the items in this bag if they do not already exist by comparing keys. The opposite of replace.

Example:

Bag::from(['foo' => 'bar'])
    ->defaults(['foo' => 'other', 'hello' => 'world']);
// => Bag of ['foo' => 'bar', 'hello' => 'world']

Parameters

iterable $collection The collection from which items will be extracted

Return Value

Bag

Bag defaultsRecursive(iterable $collection)

Returns a bag with the items from the $collection recursively added to the items in this bag if they do not already exist by comparing keys. The opposite of replaceRecursive.

Parameters

iterable $collection The collection from which items will be extracted

Return Value

Bag

Bag merge(iterable $list)

Returns a bag with the items merged with the given list.

Note: This should only be used for lists (zero indexed and sequential items). For associative arrays, use replace instead.

Parameters

iterable $list The list of items to merge

Return Value

Bag

Bag slice(int $offset, int|null $length = null, bool $preserveKeys = false)

Returns a bag with a slice of $length items starting at position $offset extracted from this bag.

Parameters

int $offset If positive, the offset to start from. If negative, the bag will start that far from the end of the list.
int|null $length If positive, the maximum number of items to return. If negative, the bag will stop that far from the end of the list. If null, the bag will have everything from the $offset to the end of the list.
bool $preserveKeys Whether to preserve keys in the resulting bag or not

Return Value

Bag

Bag[] partition(callable $predicate)

Partitions the items into two bags according to the $predicate.

Keys are preserved in the resulting bags.

Example:

[$trueItems, $falseItems] = $bag->partition(function ($key, $item) {
    return true; // whatever logic
});

Parameters

callable $predicate Function is passed ($key, $value) and should return a boolean

Return Value

Bag[] [true bag, false bag]

Bag column(string|int|null $columnKey, string|int|null $indexKey = null)

Returns a bag with the values from a single column, identified by the $columnKey.

Optionally, an $indexKey may be provided to index the values in the returned Bag by the values from the $indexKey column.

Example:

$bag = Bag::from([
    ['id' => 10, 'name' => 'Alice'],
    ['id' => 20, 'name' => 'Bob'],
    ['id' => 30, 'name' => 'Carson'],
]);

$bag->column('name');
// => Bag of ['Alice', 'Bob', 'Carson']

$bag->column('name', 'id');
// => Bag of [10 => 'Alice', 20 => 'Bob', 30 => 'Carson']

Parameters

string|int|null $columnKey The key of the values to return or null for no change
string|int|null $indexKey The key of the keys to return or null for no change

Return Value

Bag

Bag flip()

Returns a bag with all keys exchanged with their associated values.

If a value has several occurrences, the latest key will be used as its value, and all others will be lost.

Return Value

Bag

Exceptions

LogicException when values are not strings or integers

mixed reduce(callable $callback, mixed $initial = null)

Iteratively reduce the items to a single value using the $callback function.

Parameters

callable $callback Function is passed $carry (previous or initial value) and $item (value of the current iteration)
mixed $initial Initial value

Return Value

mixed The resulting value or the initial value if list is empty

Bag unique()

Returns a bag with duplicate values removed.

Return Value

Bag

Bag|Bag[] chunk(int $size, bool $preserveKeys = false)

Returns a bag with the items split into chunks.

The last chunk may contain less items.

Example:

Bag::from([1, 2, 3, 4, 5])
    ->chunk(2);
// => Bag of [Bag of [1, 2], Bag of [3, 4], Bag of [5]]

Parameters

int $size The size of each chunk
bool $preserveKeys When set to TRUE keys will be preserved. Default is FALSE which will reindex the chunk numerically.

Return Value

Bag|Bag[] Returns a multidimensional bag, with each dimension containing $size items

Bag pad(int $size, mixed $value)

Returns a bag with the items padded to the $size with the $value.

If size is positive then the array is padded on the right. If it's negative then on the left.

Examples:

$bag = Bag::from([1, 2]);

$bag->pad(4, null);
// => Bag of [1, 2, null, null]

$bag->pad(-4, null);
// => Bag of [null, null, 1, 2]

$bag->pad(2, null);
// => Bag of [1, 2]

Parameters

int $size
mixed $value

Return Value

Bag

Bag countValues()

Returns a bag with values mapped to the number of times they are in the bag.

Example:

Bag::from(['hello', 'world', 'world'])
    ->countValues();
// => Bag of ['hello' => 1, 'world' => 2]

Return Value

Bag [value => count]

Bag flatten(int $depth = 1)

Returns a bag with the items flattened.

Example:

$bag = Bag::from([[1, 2], [[3]], 4])

// Flatten one level
$bag->flatten()
// => Bag of [1, 2, [3], 4]

// Flatten all levels
$bag->flatten(INF)
// => Bag of [1, 2, 3, 4]

Parameters

int $depth How deep to flatten

Return Value

Bag

Bag randomValues(int $size)

Returns a bag with a random number of key/value pairs.

Parameters

int $size Number of pairs

Return Value

Bag

Exceptions

InvalidArgumentException when the bag is empty or the given $size is greater than the number of items

Bag randomKeys(int $size)

Returns a list with a random number of keys (as values).

Parameters

int $size Number of keys

Return Value

Bag

Exceptions

InvalidArgumentException when the bag is empty or the given $size is greater than the number of items

Bag pick(iterable|string|string[]|int|int[] $keys)

Returns a bag with only $keys.

$keys should be passed in as multiple parameters if possible. But if you have a list of keys they can be passed in as the first parameter. Note that if you can use PHP 5.6+ syntax, you can do pick(...$keys) which is preferred.

Example:

Bag::from([
    'a' => 'red',
    'b' => 'blue',
    'c' => 'green',
])
    ->pick('a', 'c', 'd');
// => Bag of ['a' => 'red', 'c' => 'green']

Parameters

iterable|string|string[]|int|int[] $keys The keys to keep

Return Value

Bag

Bag omit(iterable|string|string[]|int|int[] $keys)

Returns a bag without $keys.

$keys should be passed in as multiple parameters if possible. But if you have a list of keys they can be passed in as the first parameter. Note that if you can use PHP 5.6+ syntax, you can do omit(...$keys) which is preferred.

Example:

Bag::from([
    'a' => 'red',
    'b' => 'blue',
    'c' => 'green',
])
    ->omit('a', 'c', 'd');
// => Bag of ['b' => 'blue']

Parameters

iterable|string|string[]|int|int[] $keys The keys to remove

Return Value

Bag

Bag diff(iterable $collection, callable $comparator = null)

Returns a bag without the values that are also in $collection.

The order is determined by this bag.

Example:

Bag::from(['red', 'blue', 'green'])
    ->diff(['blue', 'black']);
// => Bag of ['red', 'green']

Keys are preserved, so lists could need to be re-indexed.

Parameters

iterable $collection Collection to check against
callable $comparator Optional three-way comparison function

Return Value

Bag

Bag diffBy(iterable $collection, callable $iteratee)

Returns a bag without the values that are also in $collection based on the $iteratee function.

Example:

$bag = Bag::from([
    ['name' => 'Alice'],
    ['name' => 'Bob'],
    ['name' => 'Carson'],
]);
$itemsToRemove = [
    ['name' => 'Bob'],
    ['name' => 'Carson'],
    ['name' => 'David'],
];

// Compare each value by its 'name' property
$bag->diffBy($itemsToRemove, function ($item) {
    return $item['name'];
});
// => Bag of [
//     ['name' => 'Alice']
// ]
// Both items with name 'Bob' and 'Carson' are removed since they are also in $itemsToRemove

Keys are preserved, so lists could need to be re-indexed.

Parameters

iterable $collection Collection to check against
callable $iteratee Function is passed ($value)

Return Value

Bag

Bag diffKeys(iterable $collection, callable $comparator = null)

Returns a bag without the keys that are also in $collection.

The order is determined by this bag.

Example:

Bag::from([
    'a' => 'red',
    'b' => 'blue',
    'c' => 'green',
])->diffKeys([
    'b' => 'value does not matter',
    'd' => 'something',
]);
// => Bag of ['a' => 'red', 'c' => 'green']

Parameters

iterable $collection Collection to check against
callable $comparator Optional three-way comparison function

Return Value

Bag

Bag diffKeysBy(iterable $collection, callable $iteratee)

Returns a bag without the keys that are also in $collection based on the $iteratee function.

Example:

$bag = Bag::from([
    'a' => 'red',
    'B' => 'blue',
    'c' => 'green',
]);
$itemsToRemove = [
    'b' => null,
    'C' => null,
    'D' => null,
];

// Compare each key case-insensitively
$bag->diffKeysBy($itemsToRemove, 'strtolower');
// => Bag of ['a' => 'red']
// Keys 'B' and 'c' are removed since all keys are compared after
// being lower-cased and 'b' and 'C' are also in $itemsToRemove

Parameters

iterable $collection Collection to check against
callable $iteratee Function is passed ($value)

Return Value

Bag

Bag intersect(iterable $collection, callable $comparator = null)

Returns a bag with only the values that are also in $collection.

Example:

Bag::from(['red', 'blue', 'green'])
    ->intersect(['blue', 'black']);
// => Bag of ['blue']

Keys are preserved, so lists could need to be re-indexed.

Parameters

iterable $collection Collection to check against
callable $comparator Optional three-way comparison function

Return Value

Bag

Bag intersectBy(iterable $collection, callable $iteratee)

Returns a bag with only the values that are also in $collection based on the $iteratee function.

Example:

$bag = Bag::from([
    ['name' => 'Alice'],
    ['name' => 'Bob'],
    ['name' => 'Carson'],
]);
$itemsToKeep = [
    ['name' => 'Bob'],
    ['name' => 'Carson'],
    ['name' => 'David'],
];

// Compare each value by its 'name' property
$bag->intersectBy($itemsToKeep, function ($item) {
    return $item['name'];
});
// => Bag of [
//     ['name' => 'Bob']
//     ['name' => 'Carson']
// ]
// Both items with name 'Bob' and 'Carson' are kept since they are also in $itemsToKeep

Keys are preserved, so lists could need to be re-indexed.

Parameters

iterable $collection Collection to check against
callable $iteratee Function is passed ($value)

Return Value

Bag

Bag intersectKeys(iterable $collection, callable $comparator = null)

Returns a bag with only the keys that are also in $collection.

Example:

Bag::from([
    'a' => 'red',
    'b' => 'blue',
    'c' => 'green',
])->intersectKeys([
    'b' => 'value does not matter',
    'd' => 'something',
]);
// => Bag of ['b' => 'blue']

Parameters

iterable $collection Collection to check against
callable $comparator Optional three-way comparison function

Return Value

Bag

Bag intersectKeysBy(iterable $collection, callable $iteratee)

Returns a bag with only the keys that are also in $collection based on the $iteratee function.

Example:

$bag = Bag::from([
    'a' => 'red',
    'B' => 'blue',
    'c' => 'green',
]);
$itemsToKeep = [
    'b' => null,
    'C' => null,
    'D' => null,
];

// Compare each key case-insensitively
$bag->intersectKeysBy($itemsToKeep, 'strtolower');
// => Bag of ['B' => 'blue', 'c' => 'green']
// Keys 'B' and 'c' are kept since all keys are compared after
// being lower-cased and 'b' and 'C' are also in $itemsToKeep

Parameters

iterable $collection Collection to check against
callable $iteratee Function is passed ($key)

Return Value

Bag

Bag sort(int $order = SORT_ASC, int $flags = SORT_REGULAR, bool $preserveKeys = false)

Returns a bag with the values sorted.

Sorting flags:

Constant Description
SORT_REGULAR compare values without changing types
SORT_NUMERIC compare values numerically
SORT_STRING compare values as strings
SORT_STRING | SORT_FLAG_CASE compare values as strings ignoring case
SORT_LOCALE_STRING compare values as strings based on the current locale
SORT_NATURAL compare values as strings using "natural ordering"
SORT_NATURAL | SORT_FLAG_CASE compare values as strings using "natural ordering" ignoring case

Parameters

int $order SORT_ASC or SORT_DESC
int $flags Sorting flags to modify the behavior
bool $preserveKeys Whether to preserve keys for maps or to re-index for lists

Return Value

Bag

Bag sortBy(callable $iteratee, int $order = SORT_ASC, bool $preserveKeys = false)

Returns a bag with the values sorted based on the $iteratee function.

Example:

$bag = Bag::from([
    ['name' => 'Bob'],
    ['name' => 'Alice'],
]);

// Sort values by "name" property
$bag->sortBy(function ($item) {
    return $item['name'];
});
// => Bag of [
//     ['name' => 'Alice']
//     ['name' => 'Bob']
// ]

Parameters

callable $iteratee Function given ($value)
int $order SORT_ASC or SORT_DESC
bool $preserveKeys Whether to preserve keys for maps or to re-index for lists

Return Value

Bag

Bag sortWith(callable $comparator, bool $preserveKeys = false)

Returns a bag with the values sorted with the $comparator.

Parameters

callable $comparator Function given ($itemA, $itemB)
bool $preserveKeys Whether to preserve keys for maps or to re-index for lists

Return Value

Bag

Bag sortKeys(int $order = SORT_ASC, int $flags = SORT_REGULAR)

Returns a bag with the keys sorted.

Sorting flags:

Constant Description
SORT_REGULAR compare values without changing types
SORT_NUMERIC compare values numerically
SORT_STRING compare values as strings
SORT_STRING | SORT_FLAG_CASE compare values as strings ignoring case
SORT_LOCALE_STRING compare values as strings based on the current locale
SORT_NATURAL compare values as strings using "natural ordering"
SORT_NATURAL | SORT_FLAG_CASE compare values as strings using "natural ordering" ignoring case

Parameters

int $order SORT_ASC or SORT_DESC
int $flags Sorting flags to modify the behavior

Return Value

Bag

Bag sortKeysBy(callable $iteratee, int $order = SORT_ASC)

Returns a bag with the keys sorted based on the $iteratee function.

Example:

$bag = Bag::from([
    'blue'  => 'a',
    'red'   => 'b',
    'black' => 'c',
]);

// Sort keys by first letter
$bag->sortKeysBy(function ($key) {
    return $key[0];
});
// Bag of ['blue' => 'a', 'black' => 'c', 'red' => 'b']

Parameters

callable $iteratee Function given ($key)
int $order SORT_ASC or SORT_DESC

Return Value

Bag

Bag sortKeysWith(callable $comparator)

Returns a bag with the keys sorted with the $comparator.

Parameters

callable $comparator Function given ($keyA, $keyB)

Return Value

Bag

Bag reverse(bool $preserveKeys = false)

Returns a bag with the items reversed.

Parameters

bool $preserveKeys If true numeric keys are preserved. Non-numeric keys are always preserved.

Return Value

Bag

Bag shuffle()

Returns a bag with the items shuffled.

Return Value

Bag

add(mixed $item) deprecated

deprecated since 1.1 and will be removed in 2.0. Use MutableBag instead.

Adds an item to the end of this bag.

Parameters

mixed $item The item to append

prepend(mixed $item) deprecated

deprecated since 1.1 and will be removed in 2.0. Use MutableBag instead.

Adds an item to the beginning of this bag.

Parameters

mixed $item The item to prepend

set(string $key, mixed $value) deprecated

deprecated since 1.1 and will be removed in 2.0. Use MutableBag instead.

Sets a item by key.

Parameters

string $key The key
mixed $value The value

setPath(string $path, mixed $value) deprecated

deprecated since 1.1 and will be removed in 2.0. Use MutableBag instead.

Sets a value using path syntax to set nested data.

Inner arrays will be created as needed to set the value.

Example:

// Set an item at a nested structure
$bag->setPath('foo/bar', 'color');

// Append to a list in a nested structure
$bag->get($data, 'foo/baz');
// => null
$bag->setPath('foo/baz/[]', 'a');
$bag->setPath('foo/baz/[]', 'b');
$bag->getPath('foo/baz');
// => ['a', 'b']

This function does not support keys that contain / or [] characters because these are special tokens used when traversing the data structure. A value may be appended to an existing array by using [] as the final key of a path.


Note: To set values in arrays that are in ArrayAccess objects their offsetGet() method needs to be able to return arrays by reference. See MutableBag for an example of this.

Parameters

string $path The path to traverse and set the value at
mixed $value The value to set

Exceptions

RuntimeException when trying to set a path that travels through a scalar value
RuntimeException when trying to set a value in an array that is in an ArrayAccess object which cannot retrieve arrays by reference

clear() deprecated

deprecated since 1.1 and will be removed in 2.0. Use MutableBag instead.

Remove all items from bag.

mixed remove(string|int $key, mixed|null $default = null) deprecated

deprecated since 1.1 and will be removed in 2.0. Use MutableBag instead.

Removes and returns the item at the specified $key from the bag.

Parameters

string|int $key The key of the item to remove
mixed|null $default The default value to return if the key is not found

Return Value

mixed The removed item or $default, if the bag did not contain the item

removeItem(mixed $item) deprecated

deprecated since 1.1 and will be removed in 2.0. Use MutableBag instead.

Removes the given item from the bag if it is found.

Parameters

mixed $item

mixed|null removeFirst() deprecated

deprecated since 1.1 and will be removed in 2.0. Use MutableBag instead.

Removes and returns the first item in the list.

Return Value

mixed|null

mixed|null removeLast() deprecated

deprecated since 1.1 and will be removed in 2.0. Use MutableBag instead.

Removes and returns the last item in the list.

Return Value

mixed|null