Functions

Table of Contents

Arrays #

append #

Append an item to array.

Usage

__::append([1, 2, 3], 4);

Result

[1, 2, 3, 4]

Arguments #

__::append(array $array, mixed $value = null): array
Name Description
array The original array
value The new item or value to append

Returns #

array

chunk #

Creates an array of elements split into groups the length of $size.

If array can’t be split evenly, the final chunk will be the remaining elements. When $preserveKeys is set to TRUE, keys will be preserved. Default is FALSE, which will reindex the chunk numerically.

Usage

__::chunk([1, 2, 3, 4, 5], 3);

Result

[[1, 2, 3], [4, 5]]

Arguments #

__::chunk(iterable $iterable, int $size = 1, bool $preserveKeys = false): array|\Generator
Name Description
iterable The original array
size The chunk size
preserveKeys Whether or not to preserve index keys

Returns #

array|\Generator

When given a \Traversable object for $iterable, a generator will be returned. Otherwise, an array will be returned.

Changelog #

  • 0.2.0 - iterable objects are now supported

Exceptions #

  • \InvalidArgumentException - when an non-array or non-traversable object is given for $iterable.
  • \Exception - when an \IteratorAggregate is given and getIterator() throws an exception.

compact #

Creates an array with all falsey values removed.

The following values are considered falsey:

  • false
  • null
  • 0
  • ""
  • undefined
  • NaN

Usage

__::compact([0, 1, false, 2, '', 3]);

Result

[1, 2, 3]

Arguments #

__::compact(iterable $iterable): array|\Generator
Name Description
iterable The array to compact

Returns #

array|\Generator

Changelog #

  • 0.2.0 - iterable objects are now supported

drop #

Creates a slice of array with n elements dropped from the beginning.

Usage

__::drop([0, 1, 3, 5], 2);

Result

[3, 5]

Arguments #

__::drop(iterable $input, int $number = 1): array|\Generator
Name Description
input The array or iterable to query.
number The number of elements to drop.

Returns #

array|\Generator

Changelog #

  • 0.2.0 - iterable objects are now supported

dropRight #

Creates a slice of an array with n elements dropped from the end.

If the provided iterator is an array, then an array will be returned. Otherwise, a Generator will be returned. In this latter case, the entire iterable will be buffered in memory. If the iterable contains many elements, then this could cause memory issues.

Usage

__::dropRight([0, 1, 3, 5], 2);

Result

[0, 1]

Arguments #

__::dropRight(iterable $input, int $number = 1): array|\Generator
Name Description
input The array to query.
number The number of elements to drop.

Returns #

array|\Generator

An array containing a subset of the input array with front items matching the condition removed. If the provided iterable is not an array, then a Generator will be returned.

Changelog #

  • 0.2.3 - added to Bottomline

dropRightWhile #

Creates a slice of the provided array with all elements matching the condition removed from the end.

If the provided iterator is an array, then an array will be returned. Otherwise, a Generator will be returned. In this latter case, the entire iterable will be buffered in memory. If the iterable contains many elements, then this could cause memory issues.

Drop by Primitive Condition

__::dropRightWhile([1, 2, 3, 3], 3);

Result

[1, 2]

Drop by Callback

__::dropRightWhile([1, 2, 3, 4, 5], static function ($item) {
    return $item > 3;
});

Result

[1, 2, 3]

Arguments #

__::dropRightWhile(iterable $input, \Closure|float|int|string|bool $condition): array|\Generator
Name Description
input An array of values.
condition Condition to drop by using either a primitive value or a callback

Returns #

array|\Generator

An array containing a subset of the input array with front items matching the condition removed. If the provided iterable is not an array, then a Generator will be returned.

Changelog #

  • 0.2.3 - added to Bottomline

dropWhile #

Creates a slice of the provided array with all elements matching the condition removed from the front.

Drop by Primitive Condition

__::dropWhile([1, 1, 2, 3, 4], 1);

Result

[2, 3, 4]

Drop by Callback

__::dropWhile([1, 2, 3, 4, 5], static function ($item) {
    return $item < 3;
});

Result

[3, 4, 5]

Arguments #

__::dropWhile(array|iterable $input, \Closure|float|int|string|bool $condition): array|\Generator
Name Description
input An array or iterable of values to look through.
condition Condition to drop by using either a primitive value or a callback.

Returns #

array|\Generator

An array containing a subset of the input array with front items matching the condition removed. If the input was not an array, then a \Generator will be returned.

Changelog #

  • 0.2.3 - added to Bottomline

flatten #

Flattens a multidimensional array or iterable.

If $shallow is set to TRUE, the array will only be flattened a single level.

Usage

__::flatten([1, 2, [3, [4]]], false);

Result

[1, 2, 3, 4]

Arguments #

__::flatten(iterable $iterable, bool $shallow = false): array|\Generator
Name Description
iterable
shallow

Returns #

array|\Generator

Changelog #

  • 0.2.0 - iterable objects are now supported

patch #

Patches array by xpath.

Usage

__::patch(
    [
        'addr' => [
            'country' => 'US',
            'zip' => 12345
        ]
    ],
    [
        '/addr/country' => 'CA',
        '/addr/zip' => 54321
    ]
);

Result

['addr' => ['country' => 'CA', 'zip' => 54321]]

Arguments #

__::patch(array $array, array $patches, string $parent = ''): array
Name Description
array The array to patch
patches List of new xpath-value pairs
parent

Returns #

array

Returns patched array

prepend #

Prepend item or value to an array.

Usage

__::prepend([1, 2, 3], 4);

Result

[4, 1, 2, 3]

Arguments #

__::prepend(array $array, mixed $value = null): array
Name Description
array
value

Returns #

array

randomize #

Shuffle an array ensuring no item remains in the same position.

Usage

__::randomize([1, 2, 3]);

Result

[2, 3, 1]

Arguments #

__::randomize(array $array): array
Name Description
array original array

Returns #

array

range #

Generate range of values based on start, end, and step.

Usage

__::range(1, 10, 2);

Result

[1, 3, 5, 7, 9]

Arguments #

__::range(int $start, int $stop = null, int $step = 1): array
Name Description
start range start
stop range end
step range step value

Returns #

array

range of values

repeat #

Generate array of repeated values.

Usage

__::repeat('foo', 3);

Result

['foo', 'foo', 'foo']

Arguments #

__::repeat(mixed $object, int $times): array
Name Description
object The object to repeat.
times How many times has to be repeated.

Returns #

array

Returns a new array of filled values.

Changelog #

  • 0.2.1 - $object typehint was changed from `string` to `mixed`

Collections #

assign #

Combines and merge collections provided with each others.

If the collections have common keys, then the last passed keys override the previous. If numerical indexes are passed, then last passed indexes override the previous.

For a recursive merge, see __::merge().

Usage

__::assign(
    [
        'color' => [
            'favorite' => 'red',
            5
        ],
        3
    ],
    [
        10,
        'color' => [
            'favorite' => 'green',
            'blue'
        ]
    ]
);

Result

[
    'color' => ['favorite' => 'green', 'blue'],
    10
]

Arguments #

__::assign(array|object $_): array|object
Name Description
_ Collections to assign.

Returns #

array|object

Assigned collection.

concat #

Combines and concat collections provided with each others.

If the collections have common keys, then the values are appended in an array. If numerical indexes are passed, then values are appended.

For a recursive merge, see __::merge().

Usage

__::concat(
    ['color' => ['favorite' => 'red', 5], 3],
    [10, 'color' => ['favorite' => 'green', 'blue']]
);

Result

[
    'color' => ['favorite' => ['green'], 5, 'blue'],
    3,
    10
]

Arguments #

__::concat(iterable|\stdClass $collection, iterable|\stdClass $_): array|\stdClass
Name Description
collection Collection to assign to.
_ N other collections to assign.

Returns #

array|\stdClass

If the first argument given to this function is an \stdClass, an \stdClass will be returned. Otherwise, an array will be returned.

Changelog #

  • 0.2.0 - added support for iterables

concatDeep #

Recursively combines and concat collections provided with each others.

If the collections have common keys, then the values are appended in an array. If numerical indexes are passed, then values are appended.

For a non-recursive concat, see __::concat().

Usage

__::concatDeep(
    ['color' => ['favorite' => 'red', 5], 3],
    [10, 'color' => ['favorite' => 'green', 'blue']]
);

Result

[
    'color' => [
        'favorite' => ['red', 'green'],
        5,
        'blue'
    ],
    3,
    10
]

Arguments #

__::concatDeep(iterable|\stdClass $collection, iterable|\stdClass $_): array|\stdClass
Name Description
collection First collection to concatDeep.
_ N other collections to concatDeep.

Returns #

array|\stdClass

A concatenated collection. When the first argument given is an \stdClass, then resulting value will be an \stdClass. Otherwise, an array will always be returned.

Changelog #

  • 0.2.0 - iterable support was added

doForEach #

Iterate over elements of the collection and invokes iteratee for each element.

The iteratee is invoked with three arguments: (value, index|key, collection). Iteratee functions may exit iteration early by explicitly returning false.

Usage

__::doForEach([1, 2, 3], function ($value, $key, $collection) {
    print_r($value)
});

Result

(Side effect: print 1, 2, 3)

Arguments #

__::doForEach(iterable|\stdClass $collection, \Closure $iteratee): void
Name Description
collection The collection to iterate over.
iteratee The function to call for each value.

doForEachRight #

Iterate over elements of the collection, from right to left, and invokes iteratee for each element.

The iteratee is invoked with three arguments: (value, index|key, collection). Iteratee functions may exit iteration early by explicitly returning false.

Usage

__::doForEachRight([1, 2, 3], function ($value, $key, $collection) {
    print_r($value);
});

Result

(Side effect: print 3, 2, 1)

Arguments #

__::doForEachRight(iterable|\stdClass $collection, \Closure $iteratee): void
Name Description
collection The collection to iterate over.
iteratee The function to call for each value.

ease #

Flattens a complex collection by mapping each ending leafs value to a key consisting of all previous indexes.

Usage

__::ease([
    'foo' => ['bar' => 'ter'],
    'baz' => ['b', 'z']
]);

Result

[
    'foo.bar' => 'ter',
    'baz.0' => 'b',
    'baz.1' => 'z'
]

Arguments #

__::ease(iterable $collection, string $glue = '.'): array
Name Description
collection array of values
glue glue between key path

Returns #

array

flatten collection

Changelog #

  • 0.2.0 - added support for iterables

every #

Checks if predicate returns truthy for all elements of collection.

Iteration is stopped once predicate returns falsey.

Usage

__::every([1, 3, 4], function ($value, $key, $collection) {
    return is_int($v);
});

Result

true

Arguments #

__::every(iterable|\stdClass $collection, \Closure|null $iteratee = null): bool
Name Description
collection The collection to iterate over.
iteratee The function to call for each value.

Returns #

bool

Changelog #

  • 0.2.4 - $iteratee is now optional and defaults to `__::identity`

filter #

Returns the values in the collection that pass the truth test.

When $closure is set to null, this function will automatically remove falsey values. When $closure is given, then values where the closure returns false will be removed.

Usage

$a = [
    ['name' => 'fred',   'age' => 32],
    ['name' => 'maciej', 'age' => 16]
];

__::filter($a, function($n) {
    return $n['age'] > 24;
});

Result

[['name' => 'fred', 'age' => 32]]

Arguments #

__::filter(iterable $iterable, \Closure|null $closure = null): array|\Generator
Name Description
iterable Array to filter
closure Closure to filter the array

Returns #

array|\Generator

When given a \Traversable object for $iterable, a generator will be returned. Otherwise, an array will be returned.

Changelog #

  • 0.2.0 - iterable objects are now supported

Exceptions #

  • \InvalidArgumentException - when an non-array or non-traversable object is given for $iterable.

find #

Return the first element that matches the given condition or $returnValue if no value is found (defaults to null).

Find by Primitive Condition in Array

$data = [
    "table"    => "trick",
    "pen"      => "defend",
    "motherly" => "wide",
    "may"      => "needle",
    "sweat"    => "cake",
    "sword"    => "defend",
];

__::find($data, "defend");

Result

"defend"

Find by Callback in an Array

$data = [
    "table"    => (object)["name" => "trick"],
    "pen"      => (object)["name" => "defend"],
    "motherly" => (object)["name" => "wide"],
    "may"      => (object)["name" => "needle"],
    "sweat"    => (object)["name" => "cake"],
    "sword"    => (object)["name" => "defend"],
];

__::find($data, static function ($object, $key, $collection) {
   return $object->name === "defend";
});

Result

$data["pen"]

Arguments #

__::find(array|iterable $collection, bool|\Closure|float|int|string $condition, mixed|null $returnValue = null): mixed|null
Name Description
collection an array or iterable of values to look through
condition condition to match using either a primitive value or a callback
returnValue the value to return if nothing matches

Returns #

mixed|null

The entity from the iterable. If no value is found, $returnValue is returned, which defaults to null.

Changelog #

  • 0.2.1 - added to bottomline

findEntry #

Find the first key/value pair of a given element that matches the given condition or null if no match is found.

Find by Primitive Condition in Array

$data = [
    "table"    => "trick",
    "pen"      => "defend",
    "motherly" => "wide",
    "may"      => "needle",
    "sweat"    => "cake",
    "sword"    => "defend",
];

__::findEntry($data, "defend");

Result

["pen", "defend"]

Find by Callback in an Array

$data = [
    "table"    => (object)["name" => "trick"],
    "pen"      => (object)["name" => "defend"],
    "motherly" => (object)["name" => "wide"],
    "may"      => (object)["name" => "needle"],
    "sweat"    => (object)["name" => "cake"],
    "sword"    => (object)["name" => "defend"],
];

__::findEntry($data, static function ($object, $key, $collection) {
   return $object->name === "defend";
});

Result

["pen", $data["pen"]]

Arguments #

__::findEntry(iterable $collection, bool|\Closure|float|int|string $condition): array|null
Name Description
collection an array or iterable of values to look through
condition condition to match using either a primitive value or a callback

Returns #

array|null

An array with two values, the 0th index is the key and the 1st index is the value. Null is returned if no entries can be found in the given collection.

Changelog #

  • 0.2.1 - added to bottomline

findIndex #

Return the index or key of the first element that matches the given condition or $returnValue if no value is found (defaults to -1).

Find Index by Primitive Condition in a Numerically Indexed Array

$data = [
    "native",
    "pale",
    "explain",
    "persuade",
    "elastic",
    "explain",
];

__::findIndex($data, "explain")

Result

2

Find Index by Primitive Condition in an Associative Array

$data = [
    "table"    => "trick",
    "pen"      => "defend",
    "motherly" => "wide",
    "may"      => "needle",
    "sweat"    => "cake",
    "sword"    => "defend",
];

__::findIndex($data, "defend")

Result

"pen"

Find by Callback Usage

$data = [
    "table"    => (object)["name" => "trick"],
    "pen"      => (object)["name" => "defend"],
    "motherly" => (object)["name" => "wide"],
    "may"      => (object)["name" => "needle"],
    "sweat"    => (object)["name" => "cake"],
    "sword"    => (object)["name" => "defend"],
];

__::findIndex($data, static function ($object, $key, $collection) {
    return $object->name === "defend";
})

Result

"pen"

Arguments #

__::findIndex(iterable $collection, bool|\Closure|float|int|string $condition, int|string $returnValue = -1): int|string
Name Description
collection an array or iterable of values to look through
condition condition to match using either a primitive value or a callback
returnValue the value to return if nothing matches

Returns #

int|string

The index where the respective value is found. When given a numerically indexed array, an int will be returned but when an associative array is given, a string will be returned. If no value is found, $returnValue is returned, which defaults to -1.

Changelog #

  • 0.2.1 - added to bottomline

findLast #

Return the last element that matches the given condition or $returnValue if no value is found (defaults to null).

Warning: If you give this function an iterator, it will convert the iterator into an array and then use that array to find the last element; this will incur a performance hit.

Find by Primitive Condition in Array

$data = [
    "table"    => "trick",
    "pen"      => "defend",
    "motherly" => "wide",
    "may"      => "needle",
    "sweat"    => "cake",
    "sword"    => "defend",
];

__::findLast($data, "defend");

Result

"defend"

Find by Callback in an Array

$data = [
    "table"    => (object)["name" => "trick"],
    "pen"      => (object)["name" => "defend"],
    "motherly" => (object)["name" => "wide"],
    "may"      => (object)["name" => "needle"],
    "sweat"    => (object)["name" => "cake"],
    "sword"    => (object)["name" => "defend"],
];

__::findLast($data, static function ($object, $key, $collection) {
   return $object->name === "defend";
});

Result

$data["sword"]

Arguments #

__::findLast(iterable $collection, bool|\Closure|float|int|string $condition, mixed|null $returnValue = null): mixed|null
Name Description
collection an array or iterable of values to look through
condition condition to match using either a primitive value or a callback
returnValue the value to return if nothing matches

Returns #

mixed|null

The entity from the iterable. If no value is found, $returnValue is returned, which defaults to null.

Changelog #

  • 0.2.1 - added to bottomline

findLastEntry #

Find the last key/value pair of a given element that matches the given condition or null if no match is found.

Find by Primitive Condition in Array

$data = [
    "table"    => "trick",
    "pen"      => "defend",
    "motherly" => "wide",
    "may"      => "needle",
    "sweat"    => "cake",
    "sword"    => "defend",
];

__::findLastEntry($data, "defend");

Result

["sword", "defend"]

Find by Callback in an Array

$data = [
    "table"    => (object)["name" => "trick"],
    "pen"      => (object)["name" => "defend"],
    "motherly" => (object)["name" => "wide"],
    "may"      => (object)["name" => "needle"],
    "sweat"    => (object)["name" => "cake"],
    "sword"    => (object)["name" => "defend"],
];

__::findLastEntry($data, static function ($object, $key, $collection) {
   return $object->name === "defend";
});

Result

["sword", $data["sword"]]

Arguments #

__::findLastEntry(iterable $collection, bool|\Closure|float|int|string $condition): array|null
Name Description
collection an array or iterable of values to look through
condition condition to match using either a primitive value or a callback

Returns #

array|null

An array with two values, the 0th index is the key and the 1st index is the value. Null is returned if no entries can be found in the given collection.

Changelog #

  • 0.2.1 - added to bottomline

findLastIndex #

Return the index or key of the last element that matches the given condition or $returnValue if no value is found (defaults to -1).

Warning: If you give this function an iterator, it will convert the iterator into an array and then use that array to find the last element; this will incur a performance hit.

Find Index by Primitive Condition in a Numerically Indexed Array

$data = [
    "native",
    "pale",
    "explain",
    "persuade",
    "elastic",
    "explain",
];

__::findIndex($data, "explain")

Result

5

Find Index by Primitive Condition in an Associative Array

$data = [
    "table"    => "trick",
    "pen"      => "defend",
    "motherly" => "wide",
    "may"      => "needle",
    "sweat"    => "cake",
    "sword"    => "defend",
];

__::findLastIndex($data, "defend")

Result

"sword"

Find by Callback Usage

$data = [
    "table"    => (object)["name" => "trick"],
    "pen"      => (object)["name" => "defend"],
    "motherly" => (object)["name" => "wide"],
    "may"      => (object)["name" => "needle"],
    "sweat"    => (object)["name" => "cake"],
    "sword"    => (object)["name" => "defend"],
];

__::findLastIndex($data, static function ($object, $key, $collection) {
    return $object->name === "defend";
})

Result

"sword"

Arguments #

__::findLastIndex(iterable $collection, bool|\Closure|float|int|string $condition, int|string $returnValue = -1): int|string
Name Description
collection an array or iterable of values to look through
condition condition to match using either a primitive value or a callback
returnValue the value to return if nothing matches

Returns #

int|string

The index where the respective value is found. When given a numerically indexed array, an int will be returned but when an associative array is given, a string will be returned. If no value is found, $returnValue is returned, which defaults to -1.

Changelog #

  • 0.2.1 - added to bottomline

first #

Gets the first element of an array/iterable. Passing n returns the first n elements.

When $count is null, only the first element will be returned.

Usage

__::first([1, 2, 3, 4, 5], 2);

Result

[1, 2]

Arguments #

__::first(iterable $array, int|null $count = null): array|mixed
Name Description
array array (or any iterable) of values
count number of values to return

Returns #

array|mixed

Changelog #

  • 0.2.0 - added support for iterables

get #

Get item of an array or object by index, accepting path (nested index).

If $collection is an object that implements the ArrayAccess interface, this function will treat it as an array instead of accessing class properties.

Use a period (.) in $path to go down a level in a multidimensional array.

Usage

__::get(['foo' => ['bar' => 'ter']], 'foo.bar');

Result

'ter'

Arguments #

__::get(array|object $collection, string $path, mixed $default = null): array|mixed|null
Name Description
collection Array of values or object
path Array key or object attribute. Use a period for depicting a new level in a multidimensional array
default Default value to return if index not exist

Returns #

array|mixed|null

getIterator #

Get an iterator from an object that supports iterators; including generators.

Arguments #

__::getIterator(\Traversable $input): \Traversable
Name Description
input

Returns #

\Traversable

Exceptions #

  • \InvalidArgumentException - when $input does not implement \Iterator or \IteratorAggregate
  • \Exception - when \IteratorAggregate::getIterator() throws an exception

groupBy #

Returns an associative array where the keys are values of $key.

Based on Chauncey McAskill’s array_group_by() function.

Group by Key Usage

__::groupBy([
        ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'School bus'],
        ['state' => 'CA', 'city' => 'San Diego', 'object' => 'Light bulb'],
        ['state' => 'CA', 'city' => 'Mountain View', 'object' => 'Space pen'],
    ],
    'state'
);

Result

[
  'IN' => [
     ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'School bus'],
  ],
  'CA' => [
     ['state' => 'CA', 'city' => 'San Diego', 'object' => 'Light bulb'],
     ['state' => 'CA', 'city' => 'Mountain View', 'object' => 'Space pen'],
  ]
]

Group by Nested Key (Dot Notation)

__::groupBy([
        ['object' => 'School bus', 'metadata' => ['state' => 'IN', 'city' => 'Indianapolis']],
        ['object' => 'Manhole', 'metadata' => ['state' => 'IN', 'city' => 'Indianapolis']],
        ['object' => 'Basketball', 'metadata' => ['state' => 'IN', 'city' => 'Plainfield']],
        ['object' => 'Light bulb', 'metadata' => ['state' => 'CA', 'city' => 'San Diego']],
        ['object' => 'Space pen', 'metadata' => ['state' => 'CA', 'city' => 'Mountain View']],
    ],
    'metadata.state'
);

Result

[
  'IN' => [
    'Indianapolis' => [
      ['object' => 'School bus', 'metadata' => ['state' => 'IN', 'city' => 'Indianapolis']],
      ['object' => 'Manhole', 'metadata' => ['state' => 'IN', 'city' => 'Indianapolis']],
    ],
    'Plainfield' => [
      ['object' => 'Basketball', 'metadata' => ['state' => 'IN', 'city' => 'Plainfield']],
    ],
  ],
  'CA' => [
    'San Diego' => [
      ['object' => 'Light bulb', 'metadata' => ['state' => 'CA', 'city' => 'San Diego']],
    ],
    'Mountain View' => [
      ['object' => 'Space pen', 'metadata' => ['state' => 'CA', 'city' => 'Mountain View']],
    ],
  ],
]

Group by Closure Usage

__::groupBy([
        (object)['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'School bus'],
        (object)['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'Manhole'],
        (object)['state' => 'CA', 'city' => 'San Diego', 'object' => 'Light bulb'],
    ],
    function ($value) {
        return $value->city;
    }
);

Result

[
  'Indianapolis' => [
     ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'School bus'],
     ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'Manhole'],
  ],
  'San Diego' => [
     ['state' => 'CA', 'city' => 'San Diego', 'object' => 'Light bulb'],
  ]
]

Arguments #

__::groupBy(iterable $iterable, int|float|string|\Closure $key): array
Name Description
iterable
key

Returns #

array

has #

Return true if $collection contains the requested $key.

In contrast to isset(), __::has() returns true if the key exists but is null.

Array Usage

 __::has(['foo' => ['bar' => 'num'], 'foz' => 'baz'], 'foo.bar');

Result

true

Object Usage

 __::hasKeys((object) ['foo' => 'bar', 'foz' => 'baz'], 'bar');

Result

false

Arguments #

__::has(array|object $collection, string|int $path): bool
Name Description
collection Array or object to search a key for
path Path to look for. Supports dot notation for traversing multiple levels.

Returns #

bool

hasKeys #

Returns true if $input contains all requested $keys. If $strict is true it also checks if $input exclusively contains the given $keys.

Usage

__::hasKeys(['foo' => 'bar', 'foz' => 'baz'], ['foo', 'foz']);

Result

true

Arguments #

__::hasKeys(array|\stdClass $collection = [], array $keys = [], bool $strict = false): bool
Name Description
collection of key values pairs
keys collection of keys to look for
strict to exclusively check

Returns #

bool

isEmpty #

Check if value is an empty array or object.

We consider any non enumerable as empty.

Usage

__::isEmpty([]);

Result

true

Arguments #

__::isEmpty(iterable|\stdClass $value): bool
Name Description
value The value to check for emptiness.

Returns #

bool

Changelog #

  • 0.2.0 - added support for iterables

last #

Get last item(s) of an array.

Usage

__::last([1, 2, 3, 4, 5], 2);

Result

[4, 5]

Arguments #

__::last(iterable $iterable, int|null $take = null): array|mixed
Name Description
iterable array of values
take number of returned values

Returns #

array|mixed

Changelog #

  • 0.2.0 - added support for iterables

map #

Returns an array of values by mapping each in collection through the iteratee.

Usage

__::map([1, 2, 3], function($value, $key, $collection) {
    return $value * 3;
});

Result

[3, 6, 9]

Arguments #

__::map(iterable|\stdClass $collection, \Closure $iteratee): array|\Generator
Name Description
collection The collection of values to map over.
iteratee The function to apply on each value.

Returns #

array|\Generator

Changelog #

  • 0.2.0 - added support for iterables

mapKeys #

Transforms the keys in a collection by running each key through the iterator.

This function throws an \Exception when the closure doesn’t return a valid key that can be used in a PHP array.

Usage

__::mapKeys(['x' => 1], function($key, $value, $collection) {
    return "{$key}_{$value}";
});

Result

['x_1' => 1]

Arguments #

__::mapKeys(iterable $iterable, \Closure|null $closure = null): array|\Generator
Name Description
iterable Array/iterable of values
closure Closure to map the keys

Returns #

array|\Generator

Changelog #

  • 0.2.0 - added support for iterables

Exceptions #

  • \InvalidArgumentException - when closure doesn’t return a valid key that can be used in PHP array

mapValues #

Transforms the values in a collection by running each value through the iterator.

Usage

__::mapValues(['x' => 1], function($value, $key, $collection) {
    return "{$key}_{$value}";
});

Result

['x' => 'x_1']

Arguments #

__::mapValues(iterable $iterable, \Closure|null $closure = null): array|\Generator
Name Description
iterable Array of values
closure Closure to map the values

Returns #

array|\Generator

Changelog #

  • 0.2.0 - added support for iterables

max #

Returns the maximum value from the collection.

If passed an iterator, max will return max value returned by the iterator.

Usage

__::max([1, 2, 3]);

Result

3

Arguments #

__::max(iterable $array): mixed
Name Description
array array

Returns #

mixed

maximum value

Changelog #

  • 0.2.0 - added support for iterables

merge #

Recursively combines and merge collections provided with each others.

  • If the collections have common keys, then the last passed keys override the previous.
  • If numerical indexes are passed, then last passed indexes override the previous.

For a non-recursive merge, see __::assign().

Usage

__::merge(
    ['color' => ['favorite' => 'red', 'model' => 3, 5], 3],
    [10, 'color' => ['favorite' => 'green', 'blue']]
);

Result

['color' => ['favorite' => 'green', 'model' => 3, 'blue'], 10]

Arguments #

__::merge(iterable|\stdClass $_): array|object
Name Description
_ Collections to merge.

Returns #

array|object

Concatenated collection.

min #

Returns the minimum value from the collection. If passed an iterator, min will return min value returned by the iterator.

Usage

__::min([1, 2, 3]);

Result

1

Arguments #

__::min(iterable $array): mixed
Name Description
array array of values

Returns #

mixed

Changelog #

  • 0.2.0 - added support for iterables

pick #

Returns an array having only keys present in the given path list.

Values for missing keys values will be filled with provided default value.

Usage

__::pick(
    [
        'a' => 1,
        'b' => ['c' => 3, 'd' => 4]
    ],
    ['a', 'b.d']
);

Result

[
    'a' => 1,
    'b' => ['d' => 4]
]

Arguments #

__::pick(iterable|\stdClass $collection = [], array $paths = [], mixed $default = null): array
Name Description
collection The collection to iterate over.
paths Array paths to pick
default The default value that will be used if the specified path does not exist.

Returns #

array

Changelog #

  • 0.2.0 - added support for iterables

pluck #

Returns an array of values belonging to a given property of each item in a collection.

Usage

$a = [
    ['foo' => 'bar',  'bis' => 'ter' ],
    ['foo' => 'bar2', 'bis' => 'ter2'],
];

__::pluck($a, 'foo');

Result

['bar', 'bar2']

Arguments #

__::pluck(iterable|\stdClass $collection, string $property): array
Name Description
collection Array or object that can be converted to array
property property name

Returns #

array

Changelog #

  • 0.2.0 - added support for iterables

reduce #

Reduces $collection to a value which is the $accumulator result of running each element in $collection thru $iteratee, where each successive invocation is supplied the return value of the previous.

If $accumulator is not given, the first element of $collection is used as the initial value.

Usage: Sum Example

__::reduce([1, 2], function ($accumulator, $value, $key, $collection) {
    return $accumulator + $value;
}, 0);

Result

3

Usage: Array Counter

$a = [
    ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'School bus'],
    ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'Manhole'],
    ['state' => 'IN', 'city' => 'Plainfield', 'object' => 'Basketball'],
    ['state' => 'CA', 'city' => 'San Diego', 'object' => 'Light bulb'],
    ['state' => 'CA', 'city' => 'Mountain View', 'object' => 'Space pen'],
];

$iteratee = function ($accumulator, $value) {
    if (isset($accumulator[$value['city']]))
        $accumulator[$value['city']]++;
    else
        $accumulator[$value['city']] = 1;
    return $accumulator;
};

__::reduce($c, $iteratee, []);

Result

[
   'Indianapolis' => 2,
   'Plainfield' => 1,
   'San Diego' => 1,
   'Mountain View' => 1,
]

Usage: Objects

$object = new \stdClass();
$object->a = 1;
$object->b = 2;
$object->c = 1;

__::reduce($object, function ($result, $value, $key) {
    if (!isset($result[$value]))
        $result[$value] = [];

    $result[$value][] = $key;

    return $result;
}, [])

Result

[
    '1' => ['a', 'c'],
    '2' => ['b']
]

Arguments #

__::reduce(iterable|\stdClass $collection, \Closure $iteratee, array|\stdClass|mixed $accumulator = null): array|\stdClass|mixed
Name Description
collection The collection to iterate over.
iteratee The function invoked per iteration.
accumulator The initial value.

Returns #

array|\stdClass|mixed

Returns the accumulated value.

Changelog #

  • 0.2.0 - added support for iterables

reduceRight #

Reduces $collection to a value which is the $accumulator result of running each element in $collection - from right to left - thru $iteratee, where each successive invocation is supplied the return value of the previous.

If $accumulator is not given, the first element of $collection is used as the initial value.

Usage

__::reduceRight(['a', 'b', 'c'], function ($accumulator, $value, $key, $collection) {
    return $accumulator . $value;
}, '');

Result

'cba'

Arguments #

__::reduceRight(iterable|\stdClass $collection, \Closure $iteratee, array|\stdClass|mixed $accumulator = null): array|\stdClass|mixed
Name Description
collection The collection to iterate over.
iteratee The function invoked per iteration.
accumulator The initial value.

Returns #

array|\stdClass|mixed

Returns the accumulated value.

Changelog #

  • 0.2.0 - added support for iterables

reverseIterable #

Return the reverse of an array or other foreach-able (Iterable).

For array it does not make a copy of it; but does make a copy to memory for other traversables.

Code (using yield) is from mpen and linepogl See https://stackoverflow.com/a/36605605/1956471

Usage

__::reverseIterable([1, 2, 3]);

Result

Generator([3, 2, 1])

Arguments #

__::reverseIterable(iterable $iterable): \Generator
Name Description
iterable

Returns #

\Generator

Changelog #

  • 0.2.0 - added support for iterables

set #

Return a new collection with the item set at index to given value. Index can be a path of nested indexes.

  • If $collection is an object that implements the ArrayAccess interface, this function will treat it as an array.
  • If a portion of path doesn’t exist, it’s created. Arrays are created for missing index in an array; objects are created for missing property in an object.

This function throws an \Exception if the path consists of a non-collection.

Usage

__::set(['foo' => ['bar' => 'ter']], 'foo.baz.ber', 'fer');

Result

['foo' => ['bar' => 'ter', 'baz' => ['ber' => 'fer']]]

Arguments #

__::set(array|iterable|object $collection, string $path, mixed $value = null): array|object
Name Description
collection Collection of values
path Key or index. Supports dot notation
value The value to set at position $key

Returns #

array|object

the new collection with the item set

Exceptions #

  • \Exception - if the path consists of a non collection

size #

Get the size of an array or \Countable object. Or get the number of properties an object has.

Usage

__::size(null)                    // false
__::size("true")                  // false; a string is not a collection
__::size([1, 2, 3])               // 3
__::size((object)[1, 2])          // 2
__::size(new ArrayIterator(5, 4)) // 2

Arguments #

__::size(mixed $value): int|false
Name Description
value

Returns #

int|false

False when the given object does not support getting its size.

Changelog #

  • 0.2.0 -

some #

Equivalent to JavaScript’s Array.prototype.some() function, this method will return true if any one item in the collection passes the callback truth test.

This method will short-circuit on the first truthy callback result.

Usage

__::some([1, 3, 5, 10, 7, 9], static function ($item, $key, $collection) {
  return $item % 2 === 0;
});

Result

true

Arguments #

__::some(iterable|\stdClass $collection, \Closure|null $callback = null): bool
Name Description
collection
callback

Returns #

bool

Changelog #

  • 0.2.4 - added to library

unease #

Builds a multidimensional collection out of a hash map using the key as indicator where to put the value.

Usage

__::unease(['foo.bar' => 'ter', 'baz.0' => 'b', , 'baz.1' => 'z']);

Result

['foo' => ['bar' => 'ter'], 'baz' => ['b', 'z']]

Arguments #

__::unease(iterable|\stdClass $collection, string $separator = '.'): array
Name Description
collection Hash map of values
separator The glue used in the keys

Returns #

array

Changelog #

  • 0.2.0 - added support for iterables

where #

Return data matching specific key value condition.

Usage

$a = [
    ['name' => 'fred',   'age' => 32],
    ['name' => 'maciej', 'age' => 16]
];

__::where($a, ['age' => 16]);

Result

[['name' => 'maciej', 'age' => 16]]

Arguments #

__::where(array|iterable $array = [], array $cond = []): array
Name Description
array array of values
cond condition in format of ['KEY'=>'VALUE']

Returns #

array

Functions #

slug #

Create a web friendly URL slug from a string.

Although supported, transliteration is discouraged because:

  1. most web browsers support UTF-8 characters in URLs
  2. transliteration causes a loss of information

Usage

__::slug('Jakieś zdanie z dużą ilością obcych znaków!');

Result

'jakies-zdanie-z-duza-iloscia-obcych-znakow'

Arguments #

__::slug(string $str, array $options = []): string
Name Description
str string to generate slug from
options method options which includes: delimiter, limit, lowercase, replacements, transliterate

Returns #

string

truncate #

Truncate string based on count of words

Usage

$string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque et mi orci.';

__::truncate($string);

Result

'Lorem ipsum dolor sit amet, ...'

Arguments #

__::truncate(string $text, int $limit): string
Name Description
text text to truncate
limit limit of words

Returns #

string

urlify #

Convert any URLs into HTML anchor tags in a string.

Usage

__::urlify("I love https://google.com");

Result

'I love <a href="https://google.com">google.com</a>'

Arguments #

__::urlify(string $string): string
Name Description
string

Returns #

string

Objects #

isArray #

Check if give value is array or not.

Arguments #

__::isArray(mixed $var): bool
Name Description
var

Returns #

bool

isCollection #

Check if the object is a collection.

A collection is either an array or an object.

Arguments #

__::isCollection(mixed $object): bool
Name Description
object

Returns #

bool

isEmail #

Check if the value is valid email.

Arguments #

__::isEmail(mixed $value): bool
Name Description
value

Returns #

bool

isEqual #

Check if the objects are equals.

Perform a deep (recursive) comparison when the parameters are arrays or objects.

Note: This method supports comparing arrays, object objects, booleans, numbers, strings. object objects are compared by their own enumerable properties (as returned by get_object_vars).

Usage

__::isEqual(['honfleur' => 1, 'rungis' => [2, 3]], ['honfleur' => 1, 'rungis' => [1, 2]]);

Result

false

Arguments #

__::isEqual(mixed $object1, mixed $object2): bool
Name Description
object1
object2

Returns #

bool

isFunction #

Check if give value is function or not.

Arguments #

__::isFunction(mixed $var): bool
Name Description
var

Returns #

bool

isIterable #

Check to see if something is iterable.

Arguments #

__::isIterable(mixed $value, bool $strict = true): bool
Name Description
value
strict Match PHP 7.1 behavior where and `\stdClass` is not iterable

Returns #

bool

isNull #

Check if give value is null or not.

Arguments #

__::isNull(mixed $var): bool
Name Description
var

Returns #

bool

isNumber #

Check if give value is number or not.

Arguments #

__::isNumber(mixed $value): bool
Name Description
value

Returns #

bool

isObject #

Check if give value is object or not.

Arguments #

__::isObject(mixed $var): bool
Name Description
var

Returns #

bool

isString #

Check if give value is string or not.

Arguments #

__::isString(mixed $var): bool
Name Description
var

Returns #

bool

Sequences #

chain #

Returns a wrapper instance, allows the value to be passed through multiple bottomline functions.

Usage

__::chain([0, 1, 2, 3, null])
    ->compact()
    ->prepend(4)
    ->value()
;

Result

[4, 1, 2, 3]

Arguments #

__::chain(mixed $initialValue): \BottomlineWrapper
Name Description
initialValue

Returns #

\BottomlineWrapper

Strings #

camelCase #

Converts string to camel case.

Usage

__::camelCase('Foo Bar');

Result

'fooBar'

Arguments #

__::camelCase(string $input): string
Name Description
input

Returns #

string

capitalize #

Converts the first character of string to upper case and the remaining to lower case.

Usage

__::capitalize('FRED');

Result

'Fred'

Arguments #

__::capitalize(string $input): string
Name Description
input

Returns #

string

kebabCase #

Converts string to kebab case.

Usage

__::kebabCase('Foo Bar');

Result

'foo-bar'

Arguments #

__::kebabCase(string $input): string
Name Description
input

Returns #

string

lowerCase #

Converts string, as space separated words, to lower case.

Usage

__::lowerCase('--Foo-Bar--');

Result

'foo bar'

Arguments #

__::lowerCase(string $input): string
Name Description
input

Returns #

string

lowerFirst #

Converts the first character of string to lower case, like lcfirst.

Usage

__::lowerFirst('Fred');

Result

'fred'

Arguments #

__::lowerFirst(string $input): string
Name Description
input

Returns #

string

snakeCase #

Converts string to snake case.

Usage

__::snakeCase('Foo Bar');

Result

'foo_bar'

Arguments #

__::snakeCase(string $input): string
Name Description
input

Returns #

string

split #

Split a string by string.

  • If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.
  • If the limit parameter is negative, all components except the last -limit are returned.
  • If the limit parameter is zero, then this is treated as 1.

Usage

__::split('a-b-c', '-', 2);

Result

['a', 'b-c']

Arguments #

__::split(string $input, string $delimiter, int $limit = 9223372036854775807): string[]
Name Description
input The string to split.
delimiter The boundary string.
limit

Returns #

string[]

startCase #

Converts string to start case, aka Title Case.

Usage

__::startCase('--foo-bar--');

Result

'Foo Bar'

Arguments #

__::startCase(string $input): string
Name Description
input

Returns #

string

toLower #

Converts string, as a whole, to lower case just like strtolower().

Usage

__::toLower('fooBar');

Result

'foobar'

Arguments #

__::toLower(string $input): string
Name Description
input

Returns #

string

toUpper #

Converts string, as a whole, to lower case just like strtoupper().

Usage

__::toUpper('fooBar');

Result

'FOOBAR'

Arguments #

__::toUpper(string $input): string
Name Description
input

Returns #

string

upperCase #

Converts string, as space separated words, to upper case.

Usage

__::upperCase('--foo-bar');

Result

'FOO BAR'

Arguments #

__::upperCase(string $input): string
Name Description
input

Returns #

string

upperFirst #

Converts the first character of string to upper case, like ucfirst().

Usage

__::upperFirst('fred');

Result

'Fred'

Arguments #

__::upperFirst(string $input): string
Name Description
input

Returns #

string

words #

Splits string into an array of its words.

Usage: Default Behavior

__::words('fred, barney, & pebbles');

Result

['fred', 'barney', 'pebbles']

Use a custom regex to define how words are split.

Usage: Custom Pattern

__::words('fred, barney, & pebbles', '/[^, ]+/');

Result

['fred', 'barney', '&', 'pebbles']

Arguments #

__::words(string $input, string|null $pattern = null): string[]
Name Description
input The string of words to split.
pattern The regex to match words.

Returns #

string[]

Utilities #

identity #

Returns the first argument it receives.

Usage

__::identity('arg1', 'arg2');

Result

'arg1'

Arguments #

__::identity(mixed $_): mixed
Name Description
_

Returns #

mixed

now #

Alias to original time() function which returns current time.

Returns #

mixed