Overview examples
<?php
Arrays::each([1, 2, 3], function(){});
Arrays::each([1, 2, 3], "\\var_dump");
Arrays::each([1, 2, 3], [$this, "foo"]);
$res = Arrays::chain([1, 2, 3])
->map(function($num){ return $num + 1; })
->filter(function($num){ return $num > 1; })
->reduce(function($carry, $num){ return $carry + $num; }, 0)
->value();
Methods _.functions
, _.extendOwn
, _.clone
are not implemented. Given we consider here JavaScript object as associative array, they are not relevant.
Method _.isElement
depends on DOM and therefore is not applicable in PHP context.
Methods _.isArguments
, _.isRegExp
, _.isUndefined
are not relevant in PHP context
Methods _.isFunction
, _.isString
, _.isNumber
, _.isFinite
, _.isNaN
, _.isBoolean
, _.isDate
, _.isError
, _.isNull
belong to the corresponded classes Dsheiko\Extras\Functions
, Dsheiko\Extras\Strings
, Dsheiko\Extras\Numbers
, Dsheiko\Extras\Booleans
, Dsheiko\Extras\Any
JavaScript-inspired methods
assign
Copy the values of all properties from one or more target arrays to a target array.
- see also.
The method works pretty much like
array_merge
except it treats consistently associative arrays with numeric keys
Parameters
{array} $array
- target array
...$sources
- source one or more arrays
Syntax
assign(array $array, ...$sources): array
Example
<?php
$res = Arrays::assign(["foo" => 1, "bar" => 2], ["bar" => 3], ["foo" => 4], ["baz" => 5]);
$res = Arrays::assign([10 => "foo", 20 => "bar"], [20 => "baz"]);
concat
Merge two or more arrays
Parameters
{array} $array
- source array
{array} ...$targets
- arrays to merge
Syntax
concat(array $array, array ...$targets): array
Example
<?php
$res = Arrays::concat([1, 2], [3, 4], [5, 6]);
copyWithin
Shallow copy part of an array to another location in the same array and returns it, without modifying its size.
Parameters
{array} $array
- source array
{int} $targetIndex
- zero based index at which to copy the sequence to
{int} $beginIndex
- (optional) zero based index at which to start copying elements from
{int} $endIndex
- (optional) zero based index at which to end copying elements from
Syntax
copyWithin(
array $array,
int $targetIndex,
int $beginIndex = 0,
int $endIndex = null
): array
Example
<?php
$res = Arrays::copyWithin([1, 2, 3, 4, 5], 0, 3, 4);
each
Iterate over a list of elements, yielding each in turn to an iteratee function
Parameters
{array} $array
- source array
{mixed} $mixed
- iteratee callback
Callback arguments
{mixed} $value
- element value
{int} $index
- zero-based element index
{array} $array
- source array
Syntax
each(array $array, mixed $mixed)
Example
<?php
$sum = 0;
Arrays::each([1, 2, 3], function ($val) use(&$sum) {
$sum += $val;
});
entries / pairs
Convert an object into a list of [key, value] pairs.
Parameters
{array} $array
- source array
Syntax
pairs(array $array): array
Example
<?php
$res = Arrays::pairs([
"foo" => "FOO",
"bar" => "BAR",
]);
every
Test whether all elements in the array pass the test implemented by the provided function.
Parameters
{array} $array
- source array
{mixed} $mixed
- predicate callback
Callback arguments
{mixed} $value
- element value
{int} $index
- zero-based element index
{array} $array
- source array
Syntax
every(array $array, mixed $mixed): bool
Example
<?php
$res = Arrays::every([1, 2, 3], function($num){ return $num > 1; });
fill
Fill all the elements of an array from a start index to an end index with a static value.
Parameters
{array} $array
- source array
{mixed} $value
- value to fill an array
{int} $beginIndex
- (optional) start index, defaults to 0
{int} $endIndex
- (optional) end index, defaults to array length
Syntax
fill(array $array, $value, int $beginIndex = 0, int $endIndex = null): array
Example
<?php
$res = Arrays::fill([1, 2, 3], 4);
$res = Arrays::fill([1, 2, 3], 4, 1);
filter
Look through each value in the list, returning an array of all the values that pass a truth test (predicate).
Parameters
{array} $array
- source array
{callable} $predicate
- predicate callback
Callback arguments
{mixed} $value
- element value
{int} $index
- zero-based element index
{array} $array
- source array
Syntax
filter(array $array, callable $predicate): array
Example
<?php
$array = Arrays::filter([1, 2, 3], function($num){ return $num > 1; });
find
Look through each value in the list, returning the first one that passes a truth test (predicate),
Parameters
{array} $array
- source array
{callable} $predicate
- predicate callback
Callback arguments
{mixed} $value
- element value
{int} $index
- zero-based element index
{array} $array
- source array
Syntax
find(array $array, callable $predicate)
Example
<?php
$value = Arrays::find([1, 2, 3], function($num){ return $num > 1; });
from
Create a new array from an array-like or iterable object
Parameters
{ArrayObject|\ArrayIterator|Traversable|Object} $collection
- source collection
Syntax
from($collection): array
Example
<?php
$res = Arrays::from(new \ArrayObject([1,2,3]));
$obj = new \ArrayObject([1,2,3]);
$res = Arrays::from($obj->getIterator());
hasOwnProperty
Return a boolean indicating whether the object has the specified property
Parameters
{array} $array
- source array
{mixed} $key
- the property to test
Syntax
hasOwnProperty(array $array, mixed $key): bool
Example
<?php
$res = Arrays::hasOwnProperty(["foo" => "FOO"], "foo");
includes
Determine whether an array includes a certain element, returning true or false as appropriate.
Parameters
{array} $array
- source array
{mixed} $searchElement
- the element to search for
{int} $fromIndex
- (optional) the position in this array at which to begin searching for searchElement.
Syntax
includes(array $array, $searchElement, int $fromIndex = null): bool
Example
<?php
$res = Arrays::includes([1, 2, 3], 2);
$res = Arrays::includes([1, 2, 3, 5, 6, 7], 2, 3);
indexOf
Return the first index at which a given element can be found in the array, or -1 if it is not present
Parameters
{array} $array
- source array
{mixed} $searchElement
- the element to search for
{int} $fromIndex
- (optional) the index to start the search at. If the index is greater than or equal to the array's length.
Syntax
indexOf(array $array, $searchElement, int $fromIndex = 0): int
Example
<?php
$src = ["ant", "bison", "camel", "duck", "bison"];
$res = Arrays::indexOf($src, "bison");
$res = Arrays::indexOf($src, "bison", 2);
is
Determine whether two values are the same value.
Parameters
{array} $array
- source array
{array} $arrayToCompare
- source array
Syntax
is(array $array, array $arrayToCompare): bool
Example
<?php
$a = [1,2,3];
$b = [1,2,3];
$res = Arrays::is($a, $b);
$a = [[["foo" => "FOO", "bar" => "BAR"]]];
$b = [[["foo" => "FOO", "bar" => "BAR"]]];
$res = Arrays::is($a, $b);
join
Join all elements of an array into a mixed and returns this mixed.
Parameters
{array} $array
- source array
{mixed} $separator
- (optional) Specifies a mixed to separate each pair of adjacent elements of the array. The separator is converted to a mixed if necessary. If omitted, the array elements are separated with a comma (",").
Syntax
join(array $array, mixed $separator = ",")
Example
<?php
$res = Arrays::join([1,2,3], ":");
keys
Return all the keys or a subset of the keys of an array
Parameters
{array} $array
- source array
{mixed} $searchValue
- (optional) if specified, then only keys containing these values are returned.
Syntax
keys(array $array, $searchValue = null): array
Example
<?php
$res = Arrays::keys(["foo" => "FOO", "bar" => "BAR"]);
$res = Arrays::keys(["foo" => "FOO", "bar" => "BAR"], "BAR");
lastIndexOf
Return the last index at which a given element can be found in the array, or -1 if it is not present.
Parameters
{array} $array
- source array
{mixed} $searchValue
- element to locate in the array.
{int} $fromIndex
- (optional) the index at which to start searching backwards. Defaults to the array's length minus one
Syntax
lastIndexOf(array $array, $searchElement, int $fromIndex = null): int
Example
<?php
$src = [2, 5, 9, 2];
$res = Arrays::lastIndexOf($src, 2);
$res = Arrays::lastIndexOf($src, 2, 2);
map
Produce a new array of values by mapping each value in list through a transformation function
Parameters
{array} $array
- source array
{mixed} $mixed
- iteratee callback
Callback arguments
{mixed} $value
- element value
{int} $index
- zero-based element index
{array} $array
- source array
Syntax
map(array $array, mixed $mixed): array
Example
<?php
$res = Arrays::map([1, 2, 3], function($num){ return $num + 1; });
$res = Arrays::chain([
"foo" => "FOO",
"bar" => "BAR",
])
->pairs()
->map(function($pair){
return $pair[0] . $pair[1];
})
->value();
of
Create a new array with a variable number of arguments, regardless of number or type of the arguments.
Parameters
{array} ...$args
- elements of which to create the array
Syntax
of(...$args): array
Example
<?php
$res = Arrays::of(1, 2, 3);
pop
Remove the last element from an array and returns that element. This method changes the length of the array.
Parameters
{array} $array
- source array
Syntax
pop(array &$array)
Example
<?php
$src = [1, 2, 3];
$res = Arrays::pop($src);
push
Add one or more elements to the end of an array and returns the new length of the array.
Parameters
{array} $array
- source array
{mixed} $value
- the elements to add to the end of the array
Syntax
push(array $array, $value): array
Example
<?php
$src = [1,2,3];
$res = Arrays::push($src, 4);
reduceRight
The right-associative version of reduce.
Parameters
{array} $array
- source array
{mixed} $mixed
- iteratee callback
{mixed} $initial
- value to use as the first argument to the first call of the mixed. If no initial value is supplied, the first element in the array will be used.
Callback arguments
{mixed} $value
- element value
{int} $index
- zero-based element index
{array} $array
- source array
Syntax
reduceRight(array $array, mixed $mixed, $initial = null)
Example
<?php
$res = Arrays::reduceRight([1,2,3], function(array $carry, int $num){
$carry[] = $num;
return $carry;
}, []);
reduce
Boil down a list of values into a single value.
Parameters
{array} $array
- source array
{mixed} $mixed
- iteratee callback
{mixed} $initial
- value to use as the first argument to the first call of the mixed. If no initial value is supplied, the first element in the array will be used.
Callback arguments
{mixed} $value
- element value
{int} $index
- zero-based element index
{array} $array
- source array
Syntax
reduce(array $array, mixed $mixed, $initial = null)
Example
<?php
$sum = Arrays::reduce([1, 2, 3], function ($carry, $num) { return $carry + $num; }, 0);
reverse
Reverse an array in place. The first array element becomes the last, and the last array element becomes the first.
Parameters
{array} $array
- source array
Syntax
reverse(array $array): array
Example
<?php
$res = Arrays::reverse([1,2,3]);
shift
Remove the first element from an array and returns that removed element. This method changes the length of the array.
Parameters
{array} $array
- source array
Syntax
shift(array &$array)
Example
<?php
$src = [1, 2, 3];
$res = Arrays::shift($src);
slice
Return a shallow copy of a portion of an array into a new array object selected
from begin to end (end not included). The original array will not be modified.
Parameters
{array} $array
- source array
{int} $beginIndex
- zero-based index at which to begin extraction.
{int} $endIndex
- (optional) zero-based index before which to end extraction.
Syntax
slice(array $array, int $beginIndex, int $endIndex = null): array
Example
<?php
$src = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
$res = Arrays::slice($src, 1, 3);
some
Test whether at least one element in the array passes the test implemented by the provided function
Parameters
{array} $array
- source array
{mixed} $mixed
- predicate callback
Callback arguments
{mixed} $value
- element value
{int} $index
- zero-based element index
{array} $array
- source array
Syntax
some(array $array, mixed $mixed): bool
Example
<?php
$res = Arrays::some([1, 2, 3], function($num){ return $num > 1; });
sort
Sort an array by values (using a user-defined comparison function when callback provided)
Parameters
{array} $array
- source array
{mixed} $mixed
- iteratee callback
Syntax
sort(array $array, mixed $mixed = null): array
Example
<?php
$res = Arrays::sort([3,2,1]);
$res = Arrays::sort([3,2,1], function($a, $b){
return $a <=> $b;
});
splice
Change the contents of an array by removing existing elements and/or adding new elements.
Parameters
{array} $array
- source array
{int} $beginIndex
- index at which to start changing the array (with origin 0)
{int} $deleteCount
- (optional) an integer indicating the number of old array elements to remove.
{array} ...$items
- (optional) the elements to add to the array, beginning at the start index.
Syntax
splice(array $array, int $beginIndex, int $deleteCount = null, ...$items): array
Example
<?php
$src = ["angel", "clown", "drum", "sturgeon"];
$res = Arrays::splice($src, 2, 1, "trumpet");
unshift
Add one or more elements to the beginning of an array and returns the new length of the array
Parameters
{array} $array
- source array
{array} ...$values
- the elements to add to the front of the array
Syntax
unshift(array &$array, ...$values)
Example
<?php
$src = [1, 2];
$src = Arrays::unshift($src, 0);
$res = Arrays::unshift($src, -2, -1);
values
Return all the values of an array
Parameters
{array} $array
- source array
Syntax
values(array $array): array
Example
<?php
$res = Arrays::values([ 5 => 1, 10 => 2, 100 => 3]);
Underscore.js\Collections methods
where
Look through each value in the list, returning an array of all the values that contain all of the key-value pairs listed in $conditions
Parameters
{array} $array
- source array
{array} $conditions
- key-value pairs to match
Syntax
where(array $array, array $conditions): array
Example
<?php
$listOfPlays = [
["title" => "Cymbeline", "author" => "Shakespeare", "year" => 1611],
["title" => "The Tempest", "author" => "Shakespeare", "year" => 1611],
["title" => "Hamlet", "author" => "Shakespeare", "year" => 1603]
];
$res = Arrays::where($listOfPlays, ["author" => "Shakespeare", "year" => 1611]);
findWhere
Looks through the list and returns the first value that matches all of the key-value
pairs listed in properties.
Parameters
{array} $array
- source array
{array} $props
- key-value pairs to match
Syntax
findWhere(array $array, array $props)
Example
<?php
$src = [
[
"foo" => "FOO",
"bar" => "BAR",
"baz" => "BAZ",
],
[
"bar" => "BAR",
"baz" => "BAZ",
],
[
"baz" => "BAZ",
]
];
$res = Arrays::findWhere($src, [
"foo" => "FOO",
"bar" => "BAR",
]);
reject
Return the values in list without the elements that the predicate passes. The opposite of filter.
Parameters
{array} $array
- source array
Syntax
reject(array $array, mixed $predicate)
Example
<?php
$res = Arrays::reject([1, 2, 3, 4, 5, 6], function ($num){
return $num % 2 == 0;
});
contains
Returns true if the value is present in the list.
Parameters
{array} $array
- source array
{mixed} $searchElement
- the element to search for
{int} $fromIndex
- (optional) the position in this array at which to begin searching for searchElement.
Syntax
contains(array $array, $searchElement, int $fromIndex = null): bool
invoke
Calls the method named by methodName on each value in the list. Any extra arguments passed
to invoke will be forwarded on to the method invocation.
Parameters
{array} $array
- source array
{mixed} $iteratee
- callback to run on every array element
{array} ...$args
- (optional) extra arguments to pass in the callback
Syntax
invoke(array $array, mixed $iteratee, ...$args): array
Example
<?php
$res = Arrays::invoke([[5, 1, 7], [3, 2, 1]], [Arrays::class, "sort"]);
pluck
A convenient version of what is perhaps the most common use-case for map:
extracting a list of property values.
Parameters
{array} $array
- source array
{mixed} $key
- source property name
Syntax
pluck(array $array, mixed $key): array
Example
<?php
$res = Arrays::pluck([
["name" => "moe", "age" => 40],
["name" => "larry", "age" => 50],
["name" => "curly", "age" => 60],
], "name");
max
Returns the maximum value in list. If an iteratee function is provided
Parameters
{array} $array
- source array
{mixed} $iteratee
- (optional) callback to compare array element
{object} $context
- (optional) context to bind to
Syntax
max(array $array, mixed $iteratee = null, $context = null)
Example
<?php
$res = Arrays::max([1,2,3]);
$res = Arrays::max([
["name" => "moe", "age" => 40],
["name" => "larry", "age" => 50],
["name" => "curly", "age" => 60],
], function($stooge){
return $stooge["age"];
});
min
Returns the minimum value in list. If an iteratee function is provided
Parameters
{array} $array
- source array
{mixed} $iteratee
- (optional) callback to compare array element
{object} $context
- (optional) context to bind to
Syntax
min(array $array, mixed $iteratee = null, $context = null)
Example
<?php
$res = Arrays::min([1,2,3]);
$res = Arrays::min([
["name" => "moe", "age" => 40],
["name" => "larry", "age" => 50],
["name" => "curly", "age" => 60],
], function($stooge){
return $stooge["age"];
});
sortBy
Return a (stably) sorted copy of list, ranked in ascending order by the results of
running each value through iteratee. iteratee may also be the mixed name of the property to sort by
Parameters
{array} $array
- source array
{mixed|mixed} $mixed
- iteratee callback or property
{object} $context
- (optional) context to bind to
Syntax
sortBy(array $array, $iteratee, $context = null): array
Example
<?php
$res = Arrays::sortBy([1, 2, 3, 4, 5, 6], function($a){
return \sin($a);
});
$res = Arrays::sortBy([
["name" => "moe", "age" => 40],
["name" => "larry", "age" => 50],
["name" => "curly", "age" => 60],
], "name");
groupBy
Split a collection into sets, grouped by the result of running each value through iterator
Parameters
{array} $array
- source array
{mixed|mixed} $mixed
- iteratee callback or property
{object} $context
- (optional) context to bind to
Syntax
groupBy(array $array, $iteratee, $context = null): array
Example
<?php
$res = Arrays::groupBy([1.3, 2.1, 2.4], function($num) { return floor($num); });
indexBy
Given a list, and an iteratee function that returns a key for each element in the list
(or a property name), returns an object with an index of each item.
Just like groupBy, but for when you know your keys are unique.
Parameters
{array} $array
- source array
{mixed|mixed} $mixed
- iteratee callback or property
{object} $context
- (optional) context to bind to
Syntax
indexBy(array $array, $iteratee, $context = null): array
Example
<?php
$res = Arrays::indexBy([
["name" => "moe", "age" => 40],
["name" => "larry", "age" => 50],
["name" => "curly", "age" => 60],
], "name");
countBy
Sort a list into groups and return a count for the number of objects in each group.
Parameters
{array} $array
- source array
{mixed|mixed} $mixed
- iteratee callback or property
{object} $context
- (optional) context to bind to
Syntax
countBy(array $array, $iteratee, $context = null): array
Example
<?php
$res = Arrays::countBy([1, 2, 3, 4, 5], function($num) {
return $num % 2 == 0 ? "even": "odd";
});
shuffle
Return a shuffled copy of the list
Parameters
{array} $array
- source array
Syntax
shuffle(array $array): array
Example
<?php
$res = Arrays::shuffle([1, 2, 3]);
sample
Produce a random sample from the list. Pass a number to return n random elements from the list.
Otherwise a single random item will be returned.
Parameters
{array} $array
- source array
{int} $count
- (optional) number of random elements
Syntax
sample(array $array, int $count = null)
Example
<?php
$res = Arrays::sample([1, 2, 3], 3);
toArray
Creates a real Array from the list
Parameters
{ArrayObject|\ArrayIterator|Traversable|Object} $collection
- source collection
Syntax
toArray($collection): array
size
Return the number of values in the list.
Parameters
{array} $array
- source array
Syntax
size(array $array): int
Example
<?php
$res = Arrays::size([
"one" => 1,
"two" => 2,
"three" => 3
]);
partition
split array into two arrays: one whose elements all satisfy predicate and one whose elements all do not satisfy predicate.
Parameters
{array} $array
- source array
mixed|mixed|Closure $mixed
- predicate callback
Syntax
partition(array $array, mixed $mixed): array
Example
<?php
$res = Arrays::partition([0, 1, 2, 3, 4, 5], function($val) {
return $val % 2;
});
Underscore.js\Arrays methods
first
Get the first value from an array regardless index order and without modifying the array
When passed in array has no element, it returns undefined, unless $defaultValue
is supplied.
Then it returns $defaultValue (when $defaultValue
is a mixed then the result of its execution)
Parameters
{array} $array
- source array
{mixed} $defaultValue
- (optional) scalar or mixed
Syntax
first(array $array, $defaultValue = null)
Example
<?php
$element = Arrays::first([1, 2, 3]);
$element = Arrays::first($arr, 1);
$element = Arrays::first($arr, function(){ return 1; });
initial
Returns everything but the last entry of the array. Especially useful on the arguments object.
Pass count to exclude the last count elements from the result.
Parameters
{array} $array
- source array
{int} $count
- (optional) number of elements to remove
Syntax
initial(array $array, int $count = 1): array
Example
<?php
$res = Arrays::initial([5, 4, 3, 2, 1]);
$res = Arrays::initial([5, 4, 3, 2, 1], 3);
last
Get the last value from an array regardless index order and without modifying the array
Parameters
{array} $array
- source array
Syntax
last(array $array): mixed
Example
<?php
$element = Arrays::last([1, 2, 3]);
rest
Returns the rest of the elements in an array. Pass an index to
return the values of the array from that index onward.
Parameters
{array} $array
- source array
{int} $count
- (optional) number of elements to remove
Syntax
rest(array $array, int $count = 1): array
Example
<?php
$res = Arrays::rest([5, 4, 3, 2, 1]);
$res = Arrays::rest([5, 4, 3, 2, 1], 3);
compact
Returns a copy of the array with all falsy values removed.
Parameters
{array} $array
- source array
Syntax
compact(array $array): array
Example
<?php
$res = Arrays::compact([0, 1, false, 2, '', 3]);
flatten
Flattens a nested array (the nesting can be to any depth). If you pass shallow,
the array will only be flattened a single level.
Parameters
{array} $array
- source array
{bool} $shallow
- (optional) when true single level of flattering
Syntax
flatten(array $array, bool $shallow = false): array
Example
<?php
$res = Arrays::flatten([1, [2], [3, [[4]]]]);
$res = Arrays::flatten([1, [2], [3, [[4]]]], true);
without
Returns a copy of the array with all instances of the values removed.
Parameters
{array} $array
- source array
{array} $values
- values to remove
Syntax
without(array $array, ...$values): array
Example
<?php
$res = Arrays::without([1, 2, 1, 0, 3, 1, 4], 0, 1);
union
Computes the union of the passed-in arrays: the list of unique items,
in order, that are present in one or more of the arrays.
Parameters
{array} ...$args
- arrays to join
Syntax
union(...$args): array
Example
<?php
$res = Arrays::union(
[1, 2, 3],
[101, 2, 1, 10],
[2, 1]
);
intersection
Computes the list of values that are the intersection of all the arrays. Each value in the result is present in each of the arrays.
Parameters
{array} $array
- source array
{array} ...$sources
- source arrays
Syntax
intersection(array $array, ...$sources): array
Example
<?php
$res = Arrays::intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
$res = Arrays::intersection(
["a" => "green", "b" => "brown", "c" => "blue", "red"],
["a" => "green", "b" => "yellow", "blue", "red"]
);
difference
Returns the values from array that are not present in the other arrays.
Parameters
{array} $array
- source array
{array} ...$sources
- source arrays
Syntax
difference(array $array, ...$sources): array
Example
<?php
$res = Arrays::difference([ 1, 2, 3, 4, 5], [5, 2, 10]);
$res = Arrays::difference(
["a" => "green", "b" => "brown", "c" => "blue", "red"],
["a" => "green", "yellow", "red"]
);
uniq
Produces a duplicate-free version of the array
Parameters
{array} $array
- source array
Syntax
uniq(array $array): array
Example
<?php
$res = Arrays::uniq([1,2,3,1,1,2]);
zip
Merges together the values of each of the arrays with the values at the corresponding position. Useful when you have separate data sources that are coordinated through matching array indexes.
Parameters
{array} $array
- source array
...$sources
- source arrays
Syntax
zip(array $array, ...$sources): array
Example
<?php
$res = Arrays::zip(
["moe", "larry", "curly"],
[30, 40, 50],
[true, false, false]
);
unzip
The opposite of zip. Given an array of arrays, returns a series of new arrays, the first of which contains all of the first elements in the input arrays, the second of which contains all of the second elements, and so on.
Parameters
{array} $array
- source array
Syntax
unzip(array $array): array
Example
<?php
$res = Arrays::unzip([["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]);
object
Converts arrays into objects. Pass either a single list of [key, value] pairs, or a list of keys,
and a list of values. If duplicate keys exist, the last value wins.
Parameters
{array} $array
- source array
{array} $value
- (optional) values array
Syntax
object(array $array, array $values = null): PlainObject
Example #1
$obj = Arrays::object([ "foo" =>
[
"bar" => [
"baz" => "BAZ"
]
]
]);
echo $obj->foo->bar->baz;
Example #2
$obj = Arrays::object([["moe", 30], ["larry", 40], ["curly", 50]]);
echo $obj->moe;
echo $obj->larry;
echo $obj->curly;
Example #3
$obj = Arrays::object(["moe", "larry", "curly"], [30, 40, 50]);
echo $obj->moe;
echo $obj->larry;
echo $obj->curly;
sortedIndex
Uses a binary search to determine the index at which the value should be inserted into the list in order to
maintain the list's sorted order. If an iteratee function is provided, it will be used to compute the sort
ranking of each value, including the value you pass. The iteratee may also be the mixed
name of the property to sort by
Parameters
{array} $array
- source array
{mixed} $value
- value to insert
{mixed|mixed} $iteratee
- (optional) iteratee callback
{object} $context
- (optional) context to bind to
Syntax
sortedIndex(array $array, $value, $iteratee = null, $context = null): int
Example #1
<?php
$res = Arrays::sortedIndex([10, 20, 30, 40, 50], 35);
Example #2
<?php
$stooges = [
["name" => "moe", "age" => 40],
["name" => "larry", "age" => 50],
["name" => "curly", "age" => 60],
];
$res = Arrays::sortedIndex($stooges, ["name" => "larry", "age" => 50], "age");
findIndex
Find index of the first element matching the condition in $mixed
Parameters
{array} $array
- source array
{mixed|mixed} $iteratee
- (optional) iteratee callback
{object} $context
- (optional) context to bind to
Syntax
findIndex(array $array, $iteratee = null, $context = null): int
Example
<?php
$inx = Arrays::findIndex([
["val" => "FOO"],
["val" => "BAR"],
], function ($item){
return $item["val"] === "BAR";
});
findLastIndex
Like findIndex but iterates the array in reverse,
returning the index closest to the end where the predicate truth test passes.
Parameters
{array} $array
- source array
{mixed|mixed} $iteratee
- (optional) iteratee callback
{object} $context
- (optional) context to bind to
Syntax
findLastIndex(array $array, $iteratee = null, $context = null): int
Example
<?php
$src = [
[
'id' => 1,
'name' => 'Ted',
'last' => 'White',
],
[
'id' => 2,
'name' => 'Bob',
'last' => 'Brown',
],
[
'id' => 3,
'name' => 'Ted',
'last' => 'Jones',
],
];
$res = Arrays::findLastIndex($src, [ "name" => "Ted" ]);
range
A function to create flexibly-numbered lists of integers, handy for each and map loops. start, if omitted, defaults to 0; step defaults to 1. Returns a list of integers from start (inclusive) to stop (exclusive), incremented (or decremented) by step, exclusive. Note that ranges that stop before they start are considered to be zero-length instead of negative — if you'd like a negative range, use a negative step.
Parameters
{int} $start
- start value
{int} $end
- (optional) end value
{int} $step
- (optional) step value
Syntax
range(int $start, int $end = null, int $step = 1): array
Example #1
<?php
$res = Arrays::range(10);
Example #2
<?php
$res = Arrays::range(1, 11);
Example #3
<?php
$res = Arrays::range(0, 30, 5);
Example #4
<?php
$res = Arrays::range(0, -10, -1);
Underscore.js\Chaining methods
chain
Returns a wrapped object. Calling methods on this object will continue to return wrapped objects until value is called.
Parameters
{array} $array
- source array
Syntax
chain($array): Arrays
Example
<?php
$res = Arrays::chain([1, 2, 3])
->map(function($num){ return $num + 1; })
->filter(function($num){ return $num > 1; })
->reduce(function($carry, $num){ return $carry + $num; }, 0)
->value();
Underscore.js\Objects methods
allKeys
Retrieve all the names of object's own and inherited properties.
Given we consider here JavaScript object as associative array, it is an alias of [keys](#keys]
Parameters
{array} $array
- source array
Syntax
allKeys(array $array): array
mapObject
Like map, but for associative arrays. Transform the value of each property in turn.
Parameters
{array} $array
- source array
{callable} $iteratee
- iteratee function
{object} $context
- (optional) context object to bind to
Syntax
mapObject(array $array, callable $iteratee, $context = null): array
Example
<?php
$res = Arrays::mapObject([
"start" => 5,
"end" => 12,
], function($val){
return $val + 5;
});
pairs
Convert an object into a list of [key, value] pairs. Alias of entries
Parameters
{array} $array
- source array
Syntax
pairs(array $array): array
Example
<?php
$res = Arrays::pairs(["foo" => "FOO", "bar" => "BAR"]);
invert
Returns a copy of the object where the keys have become the values and the values the keys. For this to work, all of your object's values should be unique and string serializable.
Parameters
{array} $array
- source array
Syntax
invert(array $array): array
Example
<?php
$res = Arrays::invert([
"Moe" => "Moses",
"Larry" => "Louis",
"Curly" => "Jerome",
]);
findKey
Similar to findIndex, but for keys in objects. Returns the key where the predicate truth test passes or undefined
Parameters
{array} $array
- source array
{callable} $iteratee
- iteratee function
{object} $context
- (optional) context object to bind to
Syntax
findKey(array $array, $iteratee = null, $context = null): string
Example
<?php
$src = [
"foo" => [
'name' => 'Ted',
'last' => 'White',
],
"bar" => [
'name' => 'Frank',
'last' => 'James',
],
"baz" => [
'name' => 'Ted',
'last' => 'Jones',
],
];
$res = Arrays::findKey($src, [ "name" => "Ted" ]);
extend
Shallowly copy all of the properties in the source objects over to the destination object, and return the destination object. Any nested objects or arrays will be copied by reference
Given we consider here JavaScript object as associative array, it's an alias of assign
Parameters
{array} ...$arrays
- arrays to merge
Syntax
extend(... $arrays): array
Example
<?php
$res = Arrays::extend(["foo" => 1, "bar" => 2], ["bar" => 3], ["foo" => 4], ["baz" => 5]);
pick
Return a copy of the object, filtered to only have values for the whitelisted keys (or array of valid keys). Alternatively accepts a predicate indicating which keys to pick.
Parameters
{array} $array
- source array
{array} ...$keys
- keys or iteratee function
Syntax
pick(array $array, ...$keys): array
Example #1
<?php
$res = Arrays::pick([
'name' => 'moe',
'age' => 50,
'userid' => 'moe1',
], 'name', 'age');
Example #2
<?php
$res = Arrays::pick([
'name' => 'moe',
'age' => 50,
'userid' => 'moe1',
], function($value){
return is_int($value);
});
omit
Return a copy of the object, filtered to omit the blacklisted keys (or array of keys). Alternatively accepts a predicate indicating which keys to omit.
Parameters
{array} $array
- source array
{array} ...$keys
- keys or iteratee function
Syntax
omit(array $array, ...$keys): array
Example #1
<?php
$res = Arrays::omit([
'name' => 'moe',
'age' => 50,
'userid' => 'moe1',
], 'userid');
Example #2
<?php
$res = Arrays::omit([
'name' => 'moe',
'age' => 50,
'userid' => 'moe1',
], function($value){
return is_int($value);
});
defaults
Fill in undefined properties in object with the first value present in the following list of defaults objects.
Parameters
{array} $array
- source array
{array} $defaults
- key-value array of defaults
Syntax
defaults(array $array, array $defaults): array
Example
<?php
$res = Arrays::defaults([
"flavor" => "chocolate"
], [
"flavor" => "vanilla",
"sprinkles" => "lots",
]);
has
Does the object contain the given key? Identical to object.hasOwnProperty(key), but uses a safe reference to the hasOwnProperty function, in case it's been overridden accidentally.
Parameters
{array} $array
- source array
{string} $key
- key to look for
Syntax
has(array $array, string $key): bool
Example
<?php
$res = Arrays::has([
"flavor" => "vanilla",
"sprinkles" => "lots",
], "flavor");
property
Returns a function that will itself return the key property of any passed-in object.
Parameters
{string} $prop
- property name
Syntax
property(string $prop): callable
Example
<?php
$stooge = [ "name" => "moe" ];
$res = Arrays::property("name")($stooge);
propertyOf
Inverse of property. Takes an object and returns a function which will return the value of a provided property.
Parameters
{array} $array
- source key-value array
Syntax
propertyOf(array $array): callable
Example
<?php
$stooge = [ "name" => "moe" ];
$res = Arrays::propertyOf($stooge)("name");
matcher
Returns a predicate function that will tell you if a passed in object contains all of the key/value properties present in attrs.
Parameters
{array} $attrs
- attributes to check
Syntax
matcher(array $attrs): callable
Example
<?php
$src = [
[
"foo" => "FOO",
"bar" => "BAR",
],
[
"bar" => "BAR",
"baz" => "BAZ",
]
];
$matcher = Arrays::matcher([
"foo" => "FOO",
"bar" => "BAR",
]);
$res = Arrays::filter($src, $matcher);
isEmpty
Returns true if an enumerable object contains no values (no enumerable own-properties).
Parameters
{array} $array
- source array
Syntax
isEmpty(array $array): bool
Example
<?php
$res = Arrays::isEmpty([]);
isEqual
Performs an optimized deep comparison between the two objects, to determine if they should be considered equal.
Parameters
{array} $array
- source array
{array} $target
- array to compare with
Syntax
isEqual(array $array, array $target): bool
Example
<?php
$res = Arrays::isEqual([
"name" => "moe",
"luckyNumbers" => [13, 27, 34],
], [
"name" => "moe",
"luckyNumbers" => [13, 27, 34],
]);
isMatch
Tells you if the keys and values in properties are contained in object.
Parameters
{array} $array
- source key-value array
{array} $attrs
- attributes to check
Syntax
isMatch(array $array, array $attrs): bool
Example
<?php
$res = Arrays::isMatch([
"foo" => "FOO",
"bar" => "BAR",
"baz" => "BAZ",
],
[
"foo" => "BAZ",
]);
isArray
Returns true if source is an array.
Parameters
{array} $array
- source array
Syntax
isArray(array $array): bool
Example
<?php
$res = Arrays::isArray([ 1, 2, 3 ]);
isObject
Returns true if value is an Object. Given we consider here JavaScript object as associative array,
it is an alias of isAssocArray
Parameters
Syntax
isObject($source): bool
Example
<?php
$res = Arrays::isObject([ "foo" => 1, "bar" => 1, ]);
Other methods
replace
Replace (similar to MYSQL REPLACE statement) an element matching the condition in predicate function with the value
If no match found, add the value to the end of array
Parameters
{array} $array
- source array
{mixed} $mixed
- predicate callback
{mixed} $element
- element to replace the match
Syntax
replace(array $array, mixed $mixed, $element): array
Example
<?php
$array = Arrays::replace([
["val" => "FOO"],
["val" => "BAR"],
], function ($item){
return $item["val"] === "BAR";
}, ["val" => "BAZ"]);
isAssocArray
Test whether array is not sequential, but associative array
Parameters
{array} $array
- source array
Syntax
isAssocArray(array $array): bool
Example
<?php
$bool = Arrays::isAssocArray([1, 2, 3]);
Overview example
<?php
$res = Strings::from( " 12345 " )
->replace("/1/", "5")
->replace("/2/", "5")
->trim()
->substr(1, 3)
->get();
echo $res;
charAt
Return a new string consisting of the single UTF-16 code unit located at the specified offset into the string.
Parameters
{string} $value
- source string
{string} $index
- index of target character
Syntax
charAt(string $value, int $index = 0): string
Example
<?php
$res = Strings::charAt("ABC", 1);
charCodeAt
Return an integer between 0 and 65535 representing the UTF-16 code unit at the given index
Parameters
{string} $value
- source string
{string} $index
- index of target character
Syntax
charCodeAt(string $value, int $index = 0): int
Example
<?php
$res = Strings::charCodeAt("ABC", 0);
concat
Concatenate the string arguments to the calling string and returns a new string.
Parameters
{string} $value
- source string
{array} ...$strings
- array of target strings
Syntax
concat(string $value, ...$strings): string
Example
<?php
$res = Strings::concat("AB", "CD", "EF");
endsWith
Determine whether a string ends with the characters of a specified string, returning true or false as appropriate.
Parameters
{string} $value
- source string
{string} $search
- substring to look for
Syntax
endsWith(string $value, string $search): bool
Example
<?php
$res = Strings::endsWith("12345", "45");
fromCharCode
Return a string created from the specified sequence of code units.
Parameters
{array} $codes
- array of char codes
Syntax
fromCharCode(...$codes): string
Example
<?php
$res = Strings::fromCharCode(65, 66, 67);
includes
- Determine whether one string may be found within another string, returning true or false as appropriate.
- see also.
Parameters
{string} $value
- source string
{string} $search
- substring to look for
{int} $position
- optionally, start position
Syntax
includes(string $value, string $search, int $position = 0): bool
Example
<?php
$res = Strings::includes("12345", "1");
indexOf
Return the index of the first occurrence of the specified value
Parameters
{string} $value
- source value
{string} $searchStr
- string to search for
{int} $fromIndex
- (optional) index to start with
Syntax
indexOf(string $value, string $searchStr, int $fromIndex = 0): int
Example
<?php
$res = Strings::indexOf("ABCD", "BC");
$res = Strings::indexOf("ABCABC", "BC", 3);
lastIndexOf
Return the index of the last occurrence of the specified value
Parameters
{string} $value
- source value
{string} $searchStr
- string to search for
{int} $fromIndex
- (optional) index to start with
Syntax
lastIndexOf(string $value, string $searchStr, int $fromIndex = 0): int
Example
<?php
$res = Strings::lastIndexOf("canal", "a");
$res = Strings::lastIndexOf("canal", "a", 2);
localeCompare
Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order
Parameters
{string} $value
- source value
{string} $compareStr
- string to compare with
Syntax
localeCompare(string $value, string $compareStr): int
Example
<?php
\setlocale (LC_COLLATE, 'de_DE');
$res = Strings::localeCompare("a", "c");
match
Retrieves the matches when matching a string against a regular expression.
Parameters
{string} $value
- source value
{string} $regexp
- regular expression to match
Syntax
match(string $value, string $regexp): null|array
Example
<?php
$res = Strings::match("A1B1C1", "/[A-Z]/");
padEnd
Pad the current string (to right) with a given string (repeated, if needed) so that the resulting string reaches a given length
Parameters
{string} $value
- source value
{int} $length
- padding length
{string} $padString
- (optional) a string to pad the source with
Syntax
padEnd(string $value, int $length, string $padString = " "): string
Example
<?php
$res = Strings::padEnd("abc", 10);
$res = Strings::padEnd("abc", 10, "foo");
padStart
Pad the current string (to left) with a given string (repeated, if needed) so that the resulting string reaches a given length
Parameters
{string} $value
- source value
{int} $length
- padding length
{string} $padString
- (optional) a string to pad the source with
Syntax
padStart(string $value, int $length, string $padString = " "): string
Example
<?php
$res = Strings::padStart("abc", 10);
$res = Strings::padStart("abc", 10, "foo");
remove
Remove substring from the string
Parameters
{string} $value
- source string
{string} $search
- substring to look for
Syntax
remove(string $value, string $search): string
Example
<?php
$res = Strings::remove("12345", "1");
repeat
Construct and return a new string which contains the specified number
of copies of the string on which it was called, concatenated together.
Parameters
{string} $value
- source string
{int} $count
- An integer between 0 and +∞: [0, +∞), indicating the number of times to repeat the string in the newly-created string that is to be returned
Syntax
repeat(string $value, int $count): string
Example
<?php
$res = Strings::repeat("abc", 2);
replace
Perform a regular expression search and replace
Parameters
{string} $value
- source string
{string} $pattern
- the pattern to search for. It can be either a string or an array with strings.
{string} $replacement
- the string or an array with strings to replace.
Syntax
replace(string $value, string $pattern, string $replacement): string
Example
<?php
$res = Strings::replace("12345", "/\d/s", "*");
slice
Extract a section of a string and returns it as a new string.
Parameters
{string} $value
- source string
{int} $beginIndex
- the zero-based index at which to begin extraction.
{int} $endIndex
- (optional) the zero-based index before which to end extraction. The character at this index will not be included.
Syntax
slice(string $value, int $beginIndex, int $endIndex = null): string
See also Difference between slice and substring
Example
<?php
$res = Strings::slice("The morning is upon us.", 1, 8);
split
Splits a string into an array of strings by separating the string into substrings,
using a specified separator string to determine where to make each split.
Parameters
{string} $value
- source string
{string} $delimiter
- specifies the string which denotes the points at which each split should occur.
Syntax
split(string $value, string $delimiter): array
Example
<?php
$res = Strings::split("a,b,c", ",");
startsWith
Determine whether a string begins with the characters of a specified string, returning true or false as appropriate.
Parameters
{string} $value
- source string
{string} $search
- substring to look for
Syntax
startsWith(string $value, string $search): bools
Example
<?php
$res = Strings::startsWith("12345", "12");
substr
Return part of a string
Parameters
{string} $value
- source string
{int} $start
- start position
{int} $length
- If length is given and is positive, the string returned will contain at most length characters beginning from start (depending on the length of string).
Syntax
substr(string $value, int $start, int $length = null): string
Example
<?php
$res = Strings::substr("12345", 1, 3);
substring
Return the part of the string between the start and end indexes, or to the end of the string.
Parameters
{string} $value
- source string
{int} $beginIndex
- the zero-based index at which to begin extraction.
{int} $endIndex
- (optional) the zero-based index before which to end extraction.
Syntax
substring(string $value, int $beginIndex, int $endIndex = null): string
See also Difference between slice and substring
Example
<?php
$value = "Mozilla";
$res = Strings::substring($value, 0, 1);
$res = Strings::substring($value, 1, 0);
toLowerCase
Return the calling string value converted to lower case.
Parameters
{string} $value
- source string
{string} $mask
- optionally, the stripped characters can also be specified using the parameter.
Syntax
toLowerCase(string $value): string
Example
<?php
$res = Strings::toLowerCase("AbC");
toUpperCase
Return the calling string value converted to upper case.
Parameters
{string} $value
- source string
{string} $mask
- optionally, the stripped characters can also be specified using the parameter.
Syntax
toUpperCase(string $value): string
Example
<?php
$res = Strings::toUpperCase("AbC");
trim
Strip whitespace (or other characters) from the beginning and end of a string
Parameters
{string} $value
- source string
{string} $mask
- optionally, the stripped characters can also be specified using the parameter.
Syntax
trim(string $value, string $mask = " \t\n\r\0\x0B"): string
Example
<?php
$res = Strings::trim(" 12345 ");
escape
Escapes a string for insertion into HTML
Parameters
{string} $value
- source string
Syntax
escape(string $string): string
Example
<?php
$res = Strings::escape("Curly, Larry & Moe");
unescape
The opposite of escape
Parameters
{string} $value
- source string
Syntax
unescape(string $string): string
Example
<?php
$res = Strings::unescape("Curly, Larry & Moe");
chain
Returns a wrapped object. Calling methods on this object will continue to return wrapped objects until value is called.
Parameters
{string} $value
- source string
Syntax
chain(string $value): Strings
Example
<?php
$res = Strings::chain( " 12345 " )
->replace("/1/", "5")
->replace("/2/", "5")
->trim()
->substr(1, 3)
->value();
echo $res;