Lodash-PHP
Lodash-PHP is a port of the Lodash JS library to PHP. It is a set of easy to use utility functions for everyday PHP projects., (*1)
Lodash-PHP tries to mimick lodash.js as close as possible, (*2)
Requirements
Lodash-PHP requires minimum PHP 7.2+, but the latest version of PHP is always recommended., (*3)
Installation
Install Lodash-PHP through composer:, (*4)
$ composer require lodash-php/lodash-php
Usage
Each method in Lodash-PHP is a separate function that can be imported and used on it's own., (*5)
<?php
use function _\each;
each([1, 2, 3], function (int $item) {
var_dump($item);
});
Lodash-PHP also comes with a global _
class that can be used globally., (*6)
<?php
_::each([1, 2, 3], function (int $item) {
var_dump($item);
});
Methods
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., (*7)
Arguments:, (*8)
@param array $array array The array to process., (*9)
@param int $number [size=1] The length of each chunk, (*10)
Return:, (*11)
@return array Returns the new array of chunks., (*12)
Example:, (*13)
<?php
use function _\chunk;
chunk(['a', 'b', 'c', 'd'], 2)
// => [['a', 'b'], ['c', 'd']]
chunk(['a', 'b', 'c', 'd'], 3)
// => [['a', 'b', 'c'], ['d']]
compact
Creates an array with all falsey values removed. The values false
, null
,
0
, ""
, undefined
, and NaN
are falsey., (*14)
Arguments:, (*15)
@param array $array The array to compact., (*16)
Return:, (*17)
@return array Returns the new array of filtered values., (*18)
Example:, (*19)
<?php
use function _\compact;
compact([0, 1, false, 2, '', 3])
// => [1, 2, 3]
concat
Creates a new array concatenating array
with any additional arrays
and/or values., (*20)
Arguments:, (*21)
@param array $array The array to concatenate., (*22)
@param array<int, mixed> $values The values to concatenate., (*23)
Return:, (*24)
@return array Returns the new concatenated array., (*25)
Example:, (*26)
<?php
use function _\concat;
$array = [1];
$other = concat($array, 2, [3], [[4]]);
var_dump($other)
// => [1, 2, 3, [4]]
var_dump($array)
// => [1]
difference
Creates an array of array
values not included in the other given arrays
using SameValueZero
for equality comparisons. The order and references of result values are
determined by the first array., (*27)
Note: Unlike pullAll
, this method returns a new array., (*28)
Arguments:, (*29)
@param array $array The array to inspect., (*30)
@param array ...$values The values to exclude., (*31)
Return:, (*32)
@return array Returns the new array of filtered values., (*33)
Example:, (*34)
<?php
use function _\difference;
difference([2, 1], [2, 3])
// => [1]
differenceBy
This method is like difference
except that it accepts iteratee
which
is invoked for each element of array
and values
to generate the criterion
by which they're compared. The order and references of result values are
determined by the first array. The iteratee is invoked with one argument:
(value)., (*35)
Note: Unlike pullAllBy
, this method returns a new array., (*36)
Arguments:, (*37)
@param array $array The array to inspect., (*38)
@param array<int, mixed> ...$values The values to exclude., (*39)
@param callable $iteratee The iteratee invoked per element., (*40)
Return:, (*41)
@return array Returns the new array of filtered values., (*42)
Example:, (*43)
<?php
use function _\differenceBy;
differenceBy([2.1, 1.2], [2.3, 3.4], 'floor')
// => [1.2]
differenceWith
This method is like difference
except that it accepts comparator
which is invoked to compare elements of array
to values
. The order and
references of result values are determined by the first array. The comparator
is invoked with two arguments: (arrVal, othVal)., (*44)
Note: Unlike pullAllWith
, this method returns a new array., (*45)
Arguments:, (*46)
@param array<int, mixed> $array The array to inspect., (*47)
@param array ...$values The values to exclude., (*48)
@param callable $comparator The comparator invoked per element., (*49)
Return:, (*50)
@return array Returns the new array of filtered values., (*51)
Example:, (*52)
<?php
use function _\differenceWith;
$objects = [[ 'x' => 1, 'y' => 2 ], [ 'x' => 2, 'y' => 1 ]]
differenceWith($objects, [[ 'x' => 1, 'y' => 2 ]], '_::isEqual')
// => [[ 'x' => 2, 'y' => 1 ]]
drop
Creates a slice of array
with n
elements dropped from the beginning., (*53)
NOTE: This function will reorder and reset the array indices, (*54)
Arguments:, (*55)
@param array $array The array to query., (*56)
@param int $n The number of elements to drop., (*57)
Return:, (*58)
@return array the slice of array
., (*59)
Example:, (*60)
<?php
use function _\drop;
drop([1, 2, 3])
// => [2, 3]
drop([1, 2, 3], 2)
// => [3]
drop([1, 2, 3], 5)
// => []
drop([1, 2, 3], 0)
// => [1, 2, 3]
dropRight
Creates a slice of array
with n
elements dropped from the end.
NOTE: This function will reorder and reset the array indices, (*61)
Arguments:, (*62)
@param array $array The array to query., (*63)
@param int $n The number of elements to drop., (*64)
Return:, (*65)
@return array the slice of array
., (*66)
Example:, (*67)
<?php
use function _\dropRight;
dropRight([1, 2, 3])
// => [1, 2]
dropRight([1, 2, 3], 2)
// => [1]
dropRight([1, 2, 3], 5)
// => []
dropRight([1, 2, 3], 0)
// => [1, 2, 3]
dropRightWhile
Creates a slice of array
excluding elements dropped from the end.
Elements are dropped until predicate
returns falsey. The predicate is
invoked with three arguments: (value, index, array)., (*68)
Arguments:, (*69)
@param array $array The array to query., (*70)
@param callable $predicate The function invoked per iteration., (*71)
Return:, (*72)
@return array the slice of array
., (*73)
Example:, (*74)
<?php
use function _\dropRightWhile;
$users = [
[ 'user' => 'barney', 'active' => false ],
[ 'user' => 'fred', 'active' => true ],
[ 'user' => 'pebbles', 'active' => true ]
]
dropRightWhile($users, function($user) { return $user['active']; })
// => objects for ['barney']
dropWhile
Creates a slice of array
excluding elements dropped from the beginning.
Elements are dropped until predicate
returns falsey. The predicate is
invoked with three arguments: (value, index, array)., (*75)
Arguments:, (*76)
@param array $array The array to query., (*77)
@param callable $predicate The function invoked per iteration., (*78)
Return:, (*79)
@return array the slice of array
., (*80)
Example:, (*81)
<?php
use function _\dropWhile;
$users = [
[ 'user' => 'barney', 'active' => true ],
[ 'user' => 'fred', 'active' => true ],
[ 'user' => 'pebbles', 'active' => false ]
]
dropWhile($users, function($user) { return $user['active']; } )
// => objects for ['pebbles']
every
Checks if predicate
returns truthy for all elements of array
.
Iteration is stopped once predicate
returns falsey. The predicate is
invoked with three arguments: (value, index, array)., (*82)
Note: This method returns true
for
empty arrays because
everything is true of
elements of empty arrays., (*83)
Arguments:, (*84)
@param iterable $collection The array to iterate over., (*85)
@param callable $predicate The function invoked per iteration., (*86)
Return:, (*87)
@return bool true
if all elements pass the predicate check, else false
., (*88)
Example:, (*89)
<?php
use function _\every;
every([true, 1, null, 'yes'], function ($value) { return is_bool($value);})
// => false
$users = [
['user' => 'barney', 'age' => 36, 'active' => false],
['user' => 'fred', 'age' => 40, 'active' => false],
];
// The `matches` iteratee shorthand.
$this->assertFalse(every($users, ['user' => 'barney', 'active' => false]));
// false
// The `matchesProperty` iteratee shorthand.
$this->assertTrue(every($users, ['active', false]));
// true
// The `property` iteratee shorthand.
$this->assertFalse(every($users, 'active'));
//false
findIndex
This method is like find
except that it returns the index of the first element predicate returns truthy for instead of the element itself., (*90)
Arguments:, (*91)
@param array $array The array to inspect., (*92)
@param callable $predicate The function invoked per iteration., (*93)
@param int $fromIndex The index to search from., (*94)
Return:, (*95)
@return int the index of the found element, else -1
., (*96)
Example:, (*97)
<?php
use function _\findIndex;
$users = [
['user' => 'barney', 'active' => false],
['user' => 'fred', 'active' => false],
['user' => 'pebbles', 'active' => true],
];
findIndex($users, function($o) { return $o['user'] s== 'barney'; });
// => 0
// The `matches` iteratee shorthand.
findIndex($users, ['user' => 'fred', 'active' => false]);
// => 1
// The `matchesProperty` iteratee shorthand.
findIndex($users, ['active', false]);
// => 0
// The `property` iteratee shorthand.
findIndex($users, 'active');
// => 2
findLastIndex
This method is like findIndex
except that it iterates over elements
of collection
from right to left., (*98)
Arguments:, (*99)
@param array $array The array to inspect., (*100)
@param mixed $predicate The function invoked per iteration., (*101)
@param int $fromIndex The index to search from., (*102)
Return:, (*103)
@return int the index of the found element, else -1
., (*104)
Example:, (*105)
<?php
use function _\findLastIndex;
$users = [
['user' => 'barney', 'active' => true ],
['user' => 'fred', 'active' => false ],
['user' => 'pebbles', 'active' => false ]
]
findLastIndex($users, function($user) { return $user['user'] === 'pebbles'; })
// => 2
flatten
Flattens array
a single level deep., (*106)
Arguments:, (*107)
@param array $array The array to flatten., (*108)
Return:, (*109)
@return array the new flattened array., (*110)
Example:, (*111)
<?php
use function _\flatten;
flatten([1, [2, [3, [4]], 5]])
// => [1, 2, [3, [4]], 5]
flattenDeep
Recursively flattens array
., (*112)
Arguments:, (*113)
@param array $array The array to flatten., (*114)
Return:, (*115)
@return array Returns the new flattened array., (*116)
Example:, (*117)
<?php
use function _\flattenDeep;
flattenDeep([1, [2, [3, [4]], 5]]);
// => [1, 2, 3, 4, 5]
flattenDepth
Recursively flatten array
up to depth
times., (*118)
Arguments:, (*119)
@param array $array The array to flatten., (*120)
@param int $depth The maximum recursion depth., (*121)
Return:, (*122)
@return array the new flattened array., (*123)
Example:, (*124)
<?php
use function _\flattenDepth;
$array = [1, [2, [3, [4]], 5]]
flattenDepth($array, 1)
// => [1, 2, [3, [4]], 5]
flattenDepth($array, 2)
// => [1, 2, 3, [4], 5]
fromPairs
The inverse of toPairs
, this method returns an object composed
from key-value pairs
., (*125)
Arguments:, (*126)
@param array $pairs The key-value pairs., (*127)
Return:, (*128)
@return \stdClass the new object., (*129)
Example:, (*130)
<?php
use function _\fromPairs;
fromPairs([['a', 1], ['b', 2]])
// => stdClass(
// 'a' => 1,
//'b' => 2,
// )
head
Gets the first element of array
., (*131)
Arguments:, (*132)
@param array $array The array to query., (*133)
Return:, (*134)
@return mixed Returns the first element of array
., (*135)
Example:, (*136)
<?php
use function _\head;
head([1, 2, 3])
// => 1
head([])
// => null
indexOf
Gets the index at which the first occurrence of value
is found in array
using SameValueZero
for equality comparisons. If fromIndex
is negative, it's used as the
offset from the end of array
., (*137)
Arguments:, (*138)
@param array $array The array to inspect., (*139)
@param mixed $value The value to search for., (*140)
@param int $fromIndex The index to search from., (*141)
Return:, (*142)
@return int the index of the matched value, else -1
., (*143)
Example:, (*144)
<?php
use function _\indexOf;
indexOf([1, 2, 1, 2], 2)
// => 1
// Search from the `fromIndex`.
indexOf([1, 2, 1, 2], 2, 2)
// => 3
initial
Gets all but the last element of array
., (*145)
Arguments:, (*146)
@param array $array The array to query., (*147)
Return:, (*148)
@return array the slice of array
., (*149)
Example:, (*150)
<?php
use function _\initial;
initial([1, 2, 3])
// => [1, 2]
intersection
Creates an array of unique values that are included in all given arrays
using SameValueZero
for equality comparisons. The order and references of result values are
determined by the first array., (*151)
Arguments:, (*152)
@param array ...$arrays, (*153)
Return:, (*154)
@return array the new array of intersecting values., (*155)
Example:, (*156)
<?php
use function _\intersection;
intersection([2, 1], [2, 3])
// => [2]
intersectionBy
This method is like intersection
except that it accepts iteratee
which is invoked for each element of each arrays
to generate the criterion
by which they're compared. The order and references of result values are
determined by the first array. The iteratee is invoked with one argument:
(value)., (*157)
Arguments:, (*158)
@param array<int, mixed> ...$arrays, (*159)
@param callable $iteratee The iteratee invoked per element., (*160)
Return:, (*161)
@return array the new array of intersecting values., (*162)
Example:, (*163)
<?php
use function _\intersectionBy;
intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor)
// => [2.1]
// The `property` iteratee shorthand.
intersectionBy([[ 'x' => 1 ]], [[ 'x' => 2 ], [ 'x' => 1 ]], 'x');
// => [[ 'x' => 1 ]]
intersectionWith
This method is like intersection
except that it accepts comparator
which is invoked to compare elements of arrays
. The order and references
of result values are determined by the first array. The comparator is
invoked with two arguments: (arrVal, othVal)., (*164)
Arguments:, (*165)
@param array ...$arrays, (*166)
@param callable $comparator The comparator invoked per element., (*167)
Return:, (*168)
@return array the new array of intersecting values., (*169)
Example:, (*170)
<?php
use function _\intersectionWith;
$objects = [[ 'x' => 1, 'y' => 2 ], [ 'x' => 2, 'y' => 1 ]]
$others = [[ 'x' => 1, 'y' => 1 ], [ 'x' => 1, 'y' => 2 ]]
intersectionWith($objects, $others, '_::isEqual')
// => [[ 'x' => 1, 'y' => 2 ]]
last
Gets the last element of array
., (*171)
Arguments:, (*172)
@param array $array The array to query., (*173)
Return:, (*174)
@return mixed Returns the last element of array
., (*175)
Example:, (*176)
<?php
use function _\last;
last([1, 2, 3])
// => 3
lastIndexOf
This method is like indexOf
except that it iterates over elements of
array
from right to left., (*177)
Arguments:, (*178)
@param array $array The array to inspect., (*179)
@param mixed $value The value to search for., (*180)
@param int $fromIndex The index to search from., (*181)
Return:, (*182)
@return int the index of the matched value, else -1
., (*183)
Example:, (*184)
<?php
use function _\lastIndexOf;
lastIndexOf([1, 2, 1, 2], 2)
// => 3
// Search from the `fromIndex`.
lastIndexOf([1, 2, 1, 2], 2, 2)
// => 1
nth
Gets the element at index n
of array
. If n
is negative, the nth
element from the end is returned., (*185)
Arguments:, (*186)
@param array $array The array to query., (*187)
@param int $n The index of the element to return., (*188)
Return:, (*189)
@return mixed Returns the nth element of array
., (*190)
Example:, (*191)
<?php
use function _\nth;
$array = ['a', 'b', 'c', 'd']
nth($array, 1)
// => 'b'
nth($array, -2)
// => 'c'
pull
Removes all given values from array
using
SameValueZero
for equality comparisons., (*192)
Note: Unlike without
, this method mutates array
. Use remove
to remove elements from an array by predicate., (*193)
Arguments:, (*194)
@param array $array The array to modify., (*195)
@param array<int, string> $values The values to remove., (*196)
Return:, (*197)
@return array, (*198)
Example:, (*199)
<?php
use function _\pull;
$array = ['a', 'b', 'c', 'a', 'b', 'c']
pull($array, 'a', 'c')
var_dump($array)
// => ['b', 'b']
pullAll
This method is like pull
except that it accepts an array of values to remove., (*200)
Note: Unlike difference
, this method mutates array
., (*201)
Arguments:, (*202)
@param array $array The array to modify., (*203)
@param array $values The values to remove., (*204)
Return:, (*205)
@return array array
., (*206)
Example:, (*207)
<?php
use function _\pullAll;
$array = ['a', 'b', 'c', 'a', 'b', 'c']
pullAll($array, ['a', 'c'])
var_dump($array)
// => ['b', 'b']
pullAllBy
This method is like pullAll
except that it accepts iteratee
which is
invoked for each element of array
and values
to generate the criterion
by which they're compared. The iteratee is invoked with one argument: (value)., (*208)
Note: Unlike differenceBy
, this method mutates array
., (*209)
Arguments:, (*210)
@param array $array The array to modify., (*211)
@param array $values The values to remove., (*212)
@param callable $iteratee The iteratee invoked per element., (*213)
Return:, (*214)
@return array array
., (*215)
Example:, (*216)
<?php
use function _\pullAllBy;
$array = [[ 'x' => 1 ], [ 'x' => 2 ], [ 'x' => 3 ], [ 'x' => 1 ]]
pullAllBy($array, [[ 'x' => 1 ], [ 'x' => 3 ]], 'x')
var_dump($array)
// => [[ 'x' => 2 ]]
pullAllWith
This method is like pullAll
except that it accepts comparator
which
is invoked to compare elements of array
to values
. The comparator is
invoked with two arguments: (arrVal, othVal)., (*217)
Note: Unlike differenceWith
, this method mutates array
., (*218)
Arguments:, (*219)
@param array $array The array to modify., (*220)
@param array $values The values to remove., (*221)
@param callable $comparator The comparator invoked per element., (*222)
Return:, (*223)
@return array array
., (*224)
Example:, (*225)
<?php
use function _\pullAllWith;
$array = [[ 'x' => 1, 'y' => 2 ], [ 'x' => 3, 'y' => 4 ], [ 'x' => 5, 'y' => 6 ]]
pullAllWith($array, [[ 'x' => 3, 'y' => 4 ]], '_\isEqual')
var_dump($array)
// => [[ 'x' => 1, 'y' => 2 ], [ 'x' => 5, 'y' => 6 ]]
pullAt
Removes elements from array
corresponding to indexes
and returns an
array of removed elements., (*226)
Note: Unlike at
, this method mutates array
., (*227)
Arguments:, (*228)
@param array $array The array to modify., (*229)
@param (int | int[]) $indexes The indexes of elements to remove., (*230)
Return:, (*231)
@return array the new array of removed elements., (*232)
Example:, (*233)
<?php
use function _\pullAt;
$array = ['a', 'b', 'c', 'd']
$pulled = pullAt($array, [1, 3])
var_dump($array)
// => ['a', 'c']
var_dump($pulled)
// => ['b', 'd']
remove
Removes all elements from array
that predicate
returns truthy for
and returns an array of the removed elements. The predicate is invoked
with three arguments: (value, index, array)., (*234)
Note: Unlike filter
, this method mutates array
. Use pull
to pull elements from an array by value., (*235)
Arguments:, (*236)
@param array $array The array to modify., (*237)
@param callable $predicate The function invoked per iteration., (*238)
Return:, (*239)
@return array the new array of removed elements., (*240)
Example:, (*241)
<?php
use function _\remove;
$array = [1, 2, 3, 4]
$evens = remove($array, function ($n) { return $n % 2 === 0; })
var_dump($array)
// => [1, 3]
var_dump($evens)
// => [2, 4]
sample
Gets a random element from array
., (*242)
Arguments:, (*243)
@param array $array The array to sample., (*244)
Return:, (*245)
@return mixed Returns the random element., (*246)
Example:, (*247)
<?php
use function _\sample;
sample([1, 2, 3, 4])
// => 2
sampleSize
Gets n
random elements at unique keys from array
up to the
size of array
., (*248)
Arguments:, (*249)
@param array $array The array to sample., (*250)
@param int $n The number of elements to sample., (*251)
Return:, (*252)
@return array the random elements., (*253)
Example:, (*254)
<?php
use function _\sampleSize;
sampleSize([1, 2, 3], 2)
// => [3, 1]
sampleSize([1, 2, 3], 4)
// => [2, 3, 1]
shuffle
Creates an array of shuffled values, (*255)
Arguments:, (*256)
@param array $array The array to shuffle., (*257)
Return:, (*258)
@return array the new shuffled array., (*259)
Example:, (*260)
<?php
use function _\shuffle;
shuffle([1, 2, 3, 4])
// => [4, 1, 3, 2]
slice
Creates a slice of array
from start
up to, but not including, end
., (*261)
Arguments:, (*262)
@param array $array The array to slice., (*263)
@param int $start The start position., (*264)
@param int $end The end position., (*265)
Return:, (*266)
@return array the slice of array
., (*267)
tail
Gets all but the first element of array
., (*268)
Arguments:, (*269)
@param array $array The array to query., (*270)
Return:, (*271)
@return array the slice of array
., (*272)
Example:, (*273)
<?php
use function _\tail;
tail([1, 2, 3])
// => [2, 3]
take
Creates a slice of array
with n
elements taken from the beginning., (*274)
Arguments:, (*275)
@param array $array The array to query., (*276)
@param int $n The number of elements to take., (*277)
Return:, (*278)
@return array the slice of array
., (*279)
Example:, (*280)
<?php
use function _\take;
take([1, 2, 3])
// => [1]
take([1, 2, 3], 2)
// => [1, 2]
take([1, 2, 3], 5)
// => [1, 2, 3]
take([1, 2, 3], 0)
// => []
takeRight
Creates a slice of array
with n
elements taken from the end., (*281)
Arguments:, (*282)
@param array $array The array to query., (*283)
@param int $n The number of elements to take., (*284)
Return:, (*285)
@return array the slice of array
., (*286)
Example:, (*287)
<?php
use function _\takeRight;
takeRight([1, 2, 3])
// => [3]
takeRight([1, 2, 3], 2)
// => [2, 3]
takeRight([1, 2, 3], 5)
// => [1, 2, 3]
takeRight([1, 2, 3], 0)
// => []
takeRightWhile
Creates a slice of array
with elements taken from the end. Elements are
taken until predicate
returns falsey. The predicate is invoked with
three arguments: (value, index, array)., (*288)
Arguments:, (*289)
@param array $array The array to query., (*290)
@param callable $predicate The function invoked per iteration., (*291)
Return:, (*292)
@return array the slice of array
., (*293)
Example:, (*294)
<?php
use function _\takeRightWhile;
$users = [
[ 'user' => 'barney', 'active' => false ],
[ 'user' => 'fred', 'active' => true ],
[ 'user' => 'pebbles', 'active' => true ]
];
takeRightWhile($users, function($value) { return $value['active']; })
// => objects for ['fred', 'pebbles']
takeWhile
Creates a slice of array
with elements taken from the beginning. Elements
are taken until predicate
returns falsey. The predicate is invoked with
three arguments: (value, index, array)., (*295)
Arguments:, (*296)
@param array $array The array to query., (*297)
@param mixed $predicate The function invoked per iteration., (*298)
Return:, (*299)
@return array the slice of array
., (*300)
Example:, (*301)
<?php
use function _\takeWhile;
$users = [
[ 'user' => 'barney', 'active' => true ],
[ 'user' => 'fred', 'active' => true ],
[ 'user' => 'pebbles', 'active' => false ]
]
takeWhile($users, function($value) { return $value['active']; })
// => objects for ['barney', 'fred']
union
Creates an array of unique values, in order, from all given arrays using
SameValueZero
for equality comparisons., (*302)
Arguments:, (*303)
@param array ...$arrays The arrays to inspect., (*304)
Return:, (*305)
@return array the new array of combined values., (*306)
Example:, (*307)
<?php
use function _\union;
union([2], [1, 2])
// => [2, 1]
unionBy
This method is like union
except that it accepts iteratee
which is
invoked for each element of each arrays
to generate the criterion by
which uniqueness is computed. Result values are chosen from the first
array in which the value occurs. The iteratee is invoked with one argument:
(value)., (*308)
Arguments:, (*309)
@param array<int, mixed> ...$arrays The arrays to inspect., (*310)
@param callable $iteratee The iteratee invoked per element., (*311)
Return:, (*312)
@return array the new array of combined values., (*313)
Example:, (*314)
<?php
use function _\unionBy;
unionBy([2.1], [1.2, 2.3], 'floor')
// => [2.1, 1.2]
// The `_::property` iteratee shorthand.
unionBy([['x' => 1]], [['x' => 2], ['x' => 1]], 'x');
// => [['x' => 1], ['x' => 2]]
unionWith
This method is like union
except that it accepts comparator
which
is invoked to compare elements of arrays
. Result values are chosen from
the first array in which the value occurs. The comparator is invoked
with two arguments: (arrVal, othVal)., (*315)
Arguments:, (*316)
@param array<int, mixed> ...$arrays The arrays to inspect., (*317)
@param callable $comparator The comparator invoked per element., (*318)
Return:, (*319)
@return array the new array of combined values., (*320)
Example:, (*321)
<?php
use function _\unionWith;
$objects = [['x' => 1, 'y' => 2], ['x' => 2, 'y' => 1]]
$others = [['x' => 1, 'y' => 1], ['x' => 1, 'y' => 2]]
unionWith($objects, $others, '_::isEqual')
// => [['x' => 1, 'y' => 2], ['x' => 2, 'y' => 1], ['x' => 1, 'y' => 1]]
uniq
Creates a duplicate-free version of an array, using
SameValueZero
for equality comparisons, in which only the first occurrence of each element
is kept. The order of result values is determined by the order they occur
in the array., (*322)
Arguments:, (*323)
@param array $array The array to inspect., (*324)
Return:, (*325)
@return array the new duplicate free array., (*326)
Example:, (*327)
<?php
use function _\uniq;
uniq([2, 1, 2])
// => [2, 1]s
uniqBy
This method is like uniq
except that it accepts iteratee
which is
invoked for each element in array
to generate the criterion by which
uniqueness is computed. The order of result values is determined by the
order they occur in the array. The iteratee is invoked with one argument:
(value)., (*328)
Arguments:, (*329)
@param array $array The array to inspect., (*330)
@param mixed $iteratee The iteratee invoked per element., (*331)
Return:, (*332)
@return array the new duplicate free array., (*333)
Example:, (*334)
<?php
use function _\uniqBy;
uniqBy([2.1, 1.2, 2.3], 'floor')
// => [2.1, 1.2]
uniqWith
This method is like uniq
except that it accepts comparator
which
is invoked to compare elements of array
. The order of result values is
determined by the order they occur in the array.The comparator is invoked
with two arguments: (arrVal, othVal)., (*335)
Arguments:, (*336)
@param array $array The array to inspect., (*337)
@param callable $comparator The comparator invoked per element., (*338)
Return:, (*339)
@return array the new duplicate free array., (*340)
Example:, (*341)
<?php
use function _\uniqWith;
$objects = [['x' => 1, 'y' => 2], ['x' => 2, 'y' => 1], ['x' => 1, 'y' => 2]]
uniqWith($objects, '_::isEqual')
// => [['x' => 1, 'y' => 2], ['x' => 2, 'y' => 1]]
unzip
This method is like zip
except that it accepts an array of grouped
elements and creates an array regrouping the elements to their pre-zip
configuration., (*342)
Arguments:, (*343)
@param array $array The array of grouped elements to process., (*344)
Return:, (*345)
@return array the new array of regrouped elements., (*346)
Example:, (*347)
<?php
use function _\unzip;
$zipped = zip(['a', 'b'], [1, 2], [true, false])
// => [['a', 1, true], ['b', 2, false]]
unzip($zipped)
// => [['a', 'b'], [1, 2], [true, false]]
unzipWith
This method is like unzip
except that it accepts iteratee
to specify
how regrouped values should be combined. The iteratee is invoked with the
elements of each group: (...group)., (*348)
Arguments:, (*349)
@param array $array The array of grouped elements to process., (*350)
@param (callable | null) $iteratee The function to combine regrouped values., (*351)
Return:, (*352)
@return array the new array of regrouped elements., (*353)
Example:, (*354)
<?php
use function _\unzipWith;
$zipped = zip([1, 2], [10, 20], [100, 200])
// => [[1, 10, 100], [2, 20, 200]]
unzipWith(zipped, '_::add')
// => [3, 30, 300]
without
Creates an array excluding all given values using
SameValueZero
for equality comparisons., (*355)
Note: Unlike pull
, this method returns a new array., (*356)
Arguments:, (*357)
@param array $array The array to inspect., (*358)
@param array<int, mixed> $values The values to exclude., (*359)
Return:, (*360)
@return array the new array of filtered values., (*361)
Example:, (*362)
<?php
use function _\without;
without([2, 1, 2, 3], 1, 2)
// => [3]
zip
Creates an array of grouped elements, the first of which contains the
first elements of the given arrays, the second of which contains the
second elements of the given arrays, and so on., (*363)
Arguments:, (*364)
@param array ...$arrays The arrays to process., (*365)
Return:, (*366)
@return array the new array of grouped elements., (*367)
Example:, (*368)
<?php
use function _\zip;
zip(['a', 'b'], [1, 2], [true, false])
// => [['a', 1, true], ['b', 2, false]]
zipObject
This method is like fromPairs
except that it accepts two arrays,
one of property identifiers and one of corresponding values., (*369)
Arguments:, (*370)
@param array $props The property identifiers., (*371)
@param array $values The property values., (*372)
Return:, (*373)
@return object the new object., (*374)
Example:, (*375)
<?php
use function _\zipObject;
zipObject(['a', 'b'], [1, 2])
/* => object(stdClass)#210 (2) {
["a"] => int(1)
["b"] => int(2)
}
*\/
zipObjectDeep
This method is like zipObject
except that it supports property paths., (*376)
Arguments:, (*377)
@param array $props The property identifiers., (*378)
@param array $values The property values., (*379)
Return:, (*380)
@return \stdClass the new object., (*381)
Example:, (*382)
<?php
use function _\zipObjectDeep;
zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2])
/* => class stdClass#20 (1) {
public $a => class stdClass#19 (1) {
public $b =>
array(2) {
[0] => class stdClass#17 (1) {
public $c => int(1)
}
[1] => class stdClass#18 (1) {
public $d => int(2)
}
}
}
}
*\/
zipWith
This method is like zip
except that it accepts iteratee
to specify
how grouped values should be combined. The iteratee is invoked with the
elements of each group: (...group)., (*383)
Arguments:, (*384)
@param array<int, (array | callable)> ...$arrays The arrays to process., (*385)
@param callable $iteratee The function to combine grouped values., (*386)
Return:, (*387)
@return array the new array of grouped elements., (*388)
Example:, (*389)
<?php
use function _\zipWith;
zipWith([1, 2], [10, 20], [100, 200], function($a, $b, $c) { return $a + $b + $c; })
// => [111, 222]
Collection
countBy
Creates an array composed of keys generated from the results of running
each element of collection
through iteratee
. The corresponding value of
each key is the number of times the key was returned by iteratee
. The
iteratee is invoked with one argument: (value)., (*390)
Arguments:, (*391)
@param iterable $collection The collection to iterate over., (*392)
@param callable $iteratee The iteratee to transform keys., (*393)
Return:, (*394)
@return array Returns the composed aggregate object., (*395)
Example:, (*396)
<?php
use function _\countBy;
countBy([6.1, 4.2, 6.3], 'floor');
// => ['6' => 2, '4' => 1]
// The `property` iteratee shorthand.
countBy(['one', 'two', 'three'], 'strlen');
// => ['3' => 2, '5' => 1]
each
Iterates over elements of 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
., (*397)
Note: As with other "Collections" methods, objects with a "length"
property are iterated like arrays. To avoid this behavior use forIn
or forOwn
for object iteration., (*398)
Arguments:, (*399)
@param (array | iterable | object) $collection The collection to iterate over., (*400)
@param callable $iteratee The function invoked per iteration., (*401)
Return:, (*402)
@return (array | object) Returns collection
., (*403)
Example:, (*404)
<?php
use function _\each;
each([1, 2], function ($value) { echo $value; })
// => Echoes `1` then `2`.
each((object) ['a' => 1, 'b' => 2], function ($value, $key) { echo $key; });
// => Echoes 'a' then 'b' (iteration order is not guaranteed).
eachRight
This method is like each
except that it iterates over elements of
collection
from right to left., (*405)
Arguments:, (*406)
@param (array | iterable | object) $collection The collection to iterate over., (*407)
@param callable $iteratee The function invoked per iteration., (*408)
Return:, (*409)
@return (array | object) Returns collection
., (*410)
Example:, (*411)
<?php
use function _\eachRight;
eachRight([1, 2], function($value) { echo $value; })
// => Echoes `2` then `1`.
filter
Iterates over elements of array
, returning an array of all elements
predicate
returns truthy for. The predicate is invoked with three
arguments: (value, index, array)., (*412)
Note: Unlike remove
, this method returns a new array., (*413)
Arguments:, (*414)
@param iterable $array The array to iterate over., (*415)
@param callable $predicate The function invoked per iteration., (*416)
Return:, (*417)
@return array the new filtered array., (*418)
Example:, (*419)
<?php
use function _\filter;
$users = [
[ 'user' => 'barney', 'age' => 36, 'active' => true],
[ 'user' => 'fred', 'age' => 40, 'active' => false]
];
filter($users, function($o) { return !$o['active']; });
// => objects for ['fred']
// The `matches` iteratee shorthand.
filter($users, ['age' => 36, 'active' => true]);
// => objects for ['barney']
// The `matchesProperty` iteratee shorthand.
filter($users, ['active', false]);
// => objects for ['fred']
// The `property` iteratee shorthand.
filter($users, 'active');
// => objects for ['barney']
find
Iterates over elements of collection
, returning the first element
predicate
returns truthy for. The predicate is invoked with three
arguments: (value, index|key, collection)., (*420)
Arguments:, (*421)
@param iterable $collection The collection to inspect., (*422)
@param callable $predicate The function invoked per iteration., (*423)
@param int $fromIndex The index to search from., (*424)
Return:, (*425)
@return mixed Returns the matched element, else null
., (*426)
Example:, (*427)
<?php
use function _\find;
$users = [
['user' => 'barney', 'age' => 36, 'active' => true],
['user' => 'fred', 'age' => 40, 'active' => false],
['user' => 'pebbles', 'age' => 1, 'active' => true]
];
find($users, function($o) { return $o['age'] < 40; });
// => object for 'barney'
// The `matches` iteratee shorthand.
find($users, ['age' => 1, 'active' => true]);
// => object for 'pebbles'
// The `matchesProperty` iteratee shorthand.
find($users, ['active', false]);
// => object for 'fred'
// The `property` iteratee shorthand.
find($users, 'active');
// => object for 'barney'
findLast
This method is like find
except that it iterates over elements of
collection
from right to left., (*428)
Arguments:, (*429)
@param iterable $collection The collection to inspect., (*430)
@param callable $predicate The function invoked per iteration., (*431)
@param int $fromIndex The index to search from., (*432)
Return:, (*433)
@return mixed Returns the matched element, else undefined
., (*434)
Example:, (*435)
<?php
use function _\findLast;
findLast([1, 2, 3, 4], function ($n) { return $n % 2 == 1; })
// => 3
flatMap
Creates a flattened array of values by running each element in collection
through iteratee
and flattening the mapped results. The iteratee is invoked
with three arguments: (value, index|key, collection)., (*436)
Arguments:, (*437)
@param iterable $collection The collection to iterate over., (*438)
@param callable $iteratee The function invoked per iteration., (*439)
Return:, (*440)
@return array the new flattened array., (*441)
Example:, (*442)
<?php
use function _\flatMap;
function duplicate($n) {
return [$n, $n]
}
flatMap([1, 2], 'duplicate')
// => [1, 1, 2, 2]
flatMapDeep
This method is like flatMap
except that it recursively flattens the
mapped results., (*443)
Arguments:, (*444)
@param iterable $collection The collection to iterate over., (*445)
@param callable $iteratee The function invoked per iteration., (*446)
Return:, (*447)
@return array Returns the new flattened array., (*448)
Example:, (*449)
<?php
use function _\flatMapDeep;
function duplicate($n) {
return [[[$n, $n]]];
}
flatMapDeep([1, 2], 'duplicate');
// => [1, 1, 2, 2]
flatMapDepth
This method is like flatMap
except that it recursively flattens the
mapped results up to depth
times., (*450)
Arguments:, (*451)
@param iterable $collection The collection to iterate over., (*452)
@param callable $iteratee The function invoked per iteration., (*453)
@param int $depth The maximum recursion depth., (*454)
Return:, (*455)
@return array the new flattened array., (*456)
Example:, (*457)
<?php
use function _\flatMapDepth;
function duplicate($n) {
return [[[$n, $n]]]
}
flatMapDepth([1, 2], 'duplicate', 2)
// => [[1, 1], [2, 2]]
groupBy
Creates an array composed of keys generated from the results of running
each element of collection
through iteratee
. The order of grouped values
is determined by the order they occur in collection
. The corresponding
value of each key is an array of elements responsible for generating the
key. The iteratee is invoked with one argument: (value)., (*458)
Arguments:, (*459)
@param iterable $collection The collection to iterate over., (*460)
@param callable $iteratee The iteratee to transform keys., (*461)
Return:, (*462)
@return array Returns the composed aggregate object., (*463)
Example:, (*464)
<?php
use function _\groupBy;
groupBy([6.1, 4.2, 6.3], 'floor');
// => ['6' => [6.1, 6.3], '4' => [4.2]]
groupBy(['one', 'two', 'three'], 'strlen');
// => ['3' => ['one', 'two'], '5' => ['three']]
invokeMap
Invokes the method at path
of each element in collection
, returning
an array of the results of each invoked method. Any additional arguments
are provided to each invoked method. If path
is a function, it's invoked
for, and this
bound to, each element in collection
., (*465)
Arguments:, (*466)
@param iterable $collection The collection to iterate over., (*467)
@param (array | callable | string) $path The path of the method to invoke or the function invoked per iteration., (*468)
@param array $args The arguments to invoke each method with., (*469)
Return:, (*470)
@return array the array of results., (*471)
Example:, (*472)
<?php
use function _\invokeMap;
invokeMap([[5, 1, 7], [3, 2, 1]], function($result) { sort($result); return $result;})
// => [[1, 5, 7], [1, 2, 3]]
invokeMap([123, 456], 'str_split')
// => [['1', '2', '3'], ['4', '5', '6']]
keyBy
Creates an object composed of keys generated from the results of running
each element of collection
through iteratee
. The corresponding value of
each key is the last element responsible for generating the key. The
iteratee is invoked with one argument: (value)., (*473)
Arguments:, (*474)
@param iterable $collection The collection to iterate over., (*475)
@param callable $iteratee The iteratee to transform keys., (*476)
Return:, (*477)
@return array the composed aggregate object., (*478)
Example:, (*479)
<?php
use function _\keyBy;
$array = [
['direction' => 'left', 'code' => 97],
['direction' => 'right', 'code' => 100],
];
keyBy($array, function ($o) { return \chr($o['code']); })
// => ['a' => ['direction' => 'left', 'code' => 97], 'd' => ['direction' => 'right', 'code' => 100]]
keyBy($array, 'direction');
// => ['left' => ['direction' => 'left', 'code' => 97], 'right' => ['direction' => 'right', 'code' => 100]]
map
Creates an array of values by running each element in collection
through
iteratee
. The iteratee is invoked with three arguments:
(value, index|key, collection)., (*480)
Many lodash-php methods are guarded to work as iteratees for methods like
_::every
, _::filter
, _::map
, _::mapValues
, _::reject
, and _::some
., (*481)
The guarded methods are:
ary
, chunk
, curry
, curryRight
, drop
, dropRight
, every
,
fill
, invert
, parseInt
, random
, range
, rangeRight
, repeat
,
sampleSize
, slice
, some
, sortBy
, split
, take
, takeRight
,
template
, trim
, trimEnd
, trimStart
, and words
, (*482)
Arguments:, (*483)
@param (array | object) $collection The collection to iterate over., (*484)
@param (callable | string | array) $iteratee The function invoked per iteration., (*485)
Return:, (*486)
@return array Returns the new mapped array., (*487)
Example:, (*488)
<?php
use function _\map;
function square(int $n) {
return $n * $n;
}
map([4, 8], $square);
// => [16, 64]
map((object) ['a' => 4, 'b' => 8], $square);
// => [16, 64] (iteration order is not guaranteed)
$users = [
[ 'user' => 'barney' ],
[ 'user' => 'fred' ]
];
// The `property` iteratee shorthand.
map($users, 'user');
// => ['barney', 'fred']
orderBy
This method is like sortBy
except that it allows specifying the sort
orders of the iteratees to sort by. If orders
is unspecified, all values
are sorted in ascending order. Otherwise, specify an order of "desc" for
descending or "asc" for ascending sort order of corresponding values., (*489)
Arguments:, (*490)
@param (iterable | null) $collection The collection to iterate over., (*491)
@param (array[] | callable[] | string[]) $iteratee The iteratee(s) to sort by., (*492)
@param string[] $orders The sort orders of iteratees
., (*493)
Return:, (*494)
@return array the new sorted array., (*495)
Example:, (*496)
<?php
use function _\orderBy;
$users = [
['user' => 'fred', 'age' => 48],
['user' => 'barney', 'age' => 34],
['user' => 'fred', 'age' => 40],
['user' => 'barney', 'age' => 36]
]
// Sort by `user` in ascending order and by `age` in descending order.
orderBy($users, ['user', 'age'], ['asc', 'desc'])
// => [['user' => 'barney', 'age' => 36], ['user' => 'barney', 'age' => 34], ['user' => 'fred', 'age' => 48], ['user' => 'fred', 'age' => 40]]
partition
Creates an array of elements split into two groups, the first of which
contains elements predicate
returns truthy for, the second of which
contains elements predicate
returns falsey for. The predicate is
invoked with one argument: (value)., (*497)
Arguments:, (*498)
@param iterable $collection The collection to iterate over., (*499)
@param callable $predicate The function invoked per iteration., (*500)
Return:, (*501)
@return array the array of grouped elements., (*502)
Example:, (*503)
<?php
use function _\partition;
$users = [
['user' => 'barney', 'age' => 36, 'active' => false],
['user' => 'fred', 'age' => 40, 'active' => true],
['user' => 'pebbles', 'age' => 1, 'active' => false]
];
partition($users, function($user) { return $user['active']; })
// => objects for [['fred'], ['barney', 'pebbles']]
reduce
Reduces collection
to a value which is the accumulated 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. The iteratee is invoked with four arguments:
(accumulator, value, index|key, collection)., (*504)
Many lodash methods are guarded to work as iteratees for methods like
reduce
, reduceRight
, and transform
., (*505)
The guarded methods are:
assign
, defaults
, defaultsDeep
, includes
, merge
, orderBy
,
and sortBy
, (*506)
Arguments:, (*507)
@param iterable $collection The collection to iterate over., (*508)
@param mixed $iteratee The function invoked per iteration., (*509)
@param mixed $accumulator The initial value., (*510)
Return:, (*511)
@return mixed Returns the accumulated value., (*512)
Example:, (*513)
<?php
use function _\reduce;
reduce([1, 2], function($sum, $n) { return $sum + $n; }, 0)
// => 3
reduce(['a' => 1, 'b' => 2, 'c' => 1], function ($result, $value, $key) {
if (!isset($result[$value])) {
$result[$value] = [];
}
$result[$value][] = $key;
return $result;
}, [])
// => ['1' => ['a', 'c'], '2' => ['b']] (iteration order is not guaranteed)
reduceRight
This method is like reduce
except that it iterates over elements of
collection
from right to left., (*514)
Arguments:, (*515)
@param iterable $collection The collection to iterate over., (*516)
@param mixed $iteratee The function invoked per iteration., (*517)
@param mixed $accumulator The initial value., (*518)
Return:, (*519)
@return mixed Returns the accumulated value., (*520)
Example:, (*521)
<?php
use function _\reduceRight;
$array = [[0, 1], [2, 3], [4, 5]];
reduceRight(array, (flattened, other) => flattened.concat(other), [])
// => [4, 5, 2, 3, 0, 1]
reject
The opposite of filter
this method returns the elements of collection
that predicate
does not return truthy for., (*522)
Arguments:, (*523)
@param iterable $collection The collection to iterate over., (*524)
@param callable $predicate The function invoked per iteration., (*525)
Return:, (*526)
@return array the new filtered array., (*527)
Example:, (*528)
<?php
use function _\reject;
$users = [
['user' => 'barney', 'active' => true],
['user' => 'fred', 'active' => false]
]
reject($users, 'active')
// => objects for ['fred']
size
Gets the size of collection
by returning its length for array
values or the number of public properties for objects., (*529)
Arguments:, (*530)
@param (array | object | string) $collection The collection to inspect., (*531)
Return:, (*532)
@return int Returns the collection size., (*533)
Example:, (*534)
<?php
use function _\size;
size([1, 2, 3]);
// => 3
size(new class { public $a = 1; public $b = 2; private $c = 3; });
// => 2
size('pebbles');
// => 7
some
Checks if predicate
returns truthy for any element of collection
.
Iteration is stopped once predicate
returns truthy. The predicate is
invoked with three arguments: (value, index|key, collection)., (*535)
Arguments:, (*536)
@param iterable $collection The collection to iterate over., (*537)
@param (callable | string | array) $predicate The function invoked per iteration., (*538)
Return:, (*539)
@return boolean Returns true
if any element passes the predicate check, else false
., (*540)
Example:, (*541)
<?php
use function _\some;
some([null, 0, 'yes', false], , function ($value) { return \is_bool($value); }));
// => true
$users = [
['user' => 'barney', 'active' => true],
['user' => 'fred', 'active' => false]
];
// The `matches` iteratee shorthand.
some($users, ['user' => 'barney', 'active' => false ]);
// => false
// The `matchesProperty` iteratee shorthand.
some($users, ['active', false]);
// => true
// The `property` iteratee shorthand.
some($users, 'active');
// => true
sortBy
Creates an array of elements, sorted in ascending order by the results of
running each element in a collection through each iteratee. This method
performs a stable sort, that is, it preserves the original sort order of
equal elements. The iteratees are invoked with one argument: (value)., (*542)
Arguments:, (*543)
@param (array | object | null) $collection The collection to iterate over., (*544)
@param (callable | callable[]) $iteratees The iteratees to sort by., (*545)
Return:, (*546)
@return array Returns the new sorted array., (*547)
Example:, (*548)
<?php
use function _\sortBy;
$users = [
[ 'user' => 'fred', 'age' => 48 ],
[ 'user' => 'barney', 'age' => 36 ],
[ 'user' => 'fred', 'age' => 40 ],
[ 'user' => 'barney', 'age' => 34 ],
];
sortBy($users, [function($o) { return $o['user']; }]);
// => [['user' => 'barney', 'age' => 36], ['user' => 'barney', 'age' => 34], ['user' => 'fred', 'age' => 48], ['user' => 'fred', 'age' => 40]]
sortBy($users, ['user', 'age']);
// => [['user' => 'barney', 'age' => 34], ['user' => 'barney', 'age' => 36], ['user' => 'fred', 'age' => 40], ['user' => 'fred', 'age' => 48]]
Date
now
Gets the timestamp of the number of milliseconds that have elapsed since the Unix epoch (1 January 1970 00:00:00 UTC)., (*549)
Arguments:, (*550)
Return:, (*551)
@return int Returns the timestamp., (*552)
Example:, (*553)
<?php
use function _\now;
now();
// => 1511180325735
Function
after
The opposite of before
; this method creates a function that invokes
func
once it's called n
or more times., (*554)
Arguments:, (*555)
@param int $n The number of calls before func
is invoked., (*556)
@param Callable $func The function to restrict., (*557)
Return:, (*558)
@return Callable Returns the new restricted function., (*559)
Example:, (*560)
<?php
use function _\after;
$saves = ['profile', 'settings'];
$done = after(count($saves), function() {
echo 'done saving!';
});
forEach($saves, function($type) use($done) {
asyncSave([ 'type' => $type, 'complete' => $done ]);
});
// => Prints 'done saving!' after the two async saves have completed.
ary
Creates a function that invokes func
, with up to n
arguments,
ignoring any additional arguments., (*561)
Arguments:, (*562)
@param callable $func The function to cap arguments for., (*563)
@param int $n The arity cap., (*564)
Return:, (*565)
@return Callable Returns the new capped function., (*566)
Example:, (*567)
<?php
use function _\ary;
map(['6', '8', '10'], ary('intval', 1));
// => [6, 8, 10]
before
Creates a function that invokes func
, with the arguments
of the created function, while it's called less than n
times. Subsequent
calls to the created function return the result of the last func
invocation., (*568)
Arguments:, (*569)
@param int $n The number of calls at which func
is no longer invoked., (*570)
@param callable $func The function to restrict., (*571)
Return:, (*572)
@return callable Returns the new restricted function., (*573)
Example:, (*574)
<?php
use function _\before;
$users = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$result = uniqBy(map($users, before(5, [$repository, 'find'])), 'id')
// => Fetch up to 4 results.
bind
Creates a function that invokes func
with the this
binding of object
and partials
prepended to the arguments it receives., (*575)
Arguments:, (*576)
@param callable $function The function to bind., (*577)
@param (object | mixed) $object The object
binding of func
., (*578)
@param array<int, mixed> $partials The arguments to be partially applied., (*579)
Return:, (*580)
@return callable Returns the new bound function., (*581)
Example:, (*582)
<?php
use function _\bind;
function greet($greeting, $punctuation) {
return $greeting . ' ' . $this->user . $punctuation;
}
$object = $object = new class {
public $user = 'fred';
};
$bound = bind('greet', $object, 'hi');
$bound('!');
// => 'hi fred!'
bindKey
Creates a function that invokes the method $function
of $object
with $partials
prepended to the arguments it receives., (*583)
This method differs from bind
by allowing bound functions to reference
methods that may be redefined or don't yet exist, (*584)
Arguments:, (*585)
@param object $object The object to invoke the method on., (*586)
@param string $function The name of the method., (*587)
@param array<int, mixed> $partials The arguments to be partially applied., (*588)
Return:, (*589)
@return callable Returns the new bound function., (*590)
Example:, (*591)
<?php
use function _\bindKey;
$object = new class {
private $user = 'fred';
function greet($greeting, $punctuation) {
return $greeting.' '.$this->user.$punctuation;
}
};
$bound = bindKey($object, 'greet', 'hi');
$bound('!');
// => 'hi fred!'
curry
Creates a function that accepts arguments of func
and either invokes
func
returning its result, if at least arity
number of arguments have
been provided, or returns a function that accepts the remaining func
arguments, and so on. The arity of func
may be specified if func.length
is not sufficient., (*592)
The _.curry.placeholder
value, which defaults to _
in monolithic builds,
may be used as a placeholder for provided arguments., (*593)
Note: This method doesn't set the "length" property of curried functions., (*594)
Arguments:, (*595)
@param callable $func The function to curry., (*596)
@param (int | null) $arity The arity of func
., (*597)
Return:, (*598)
@return callable Returns the new curried function., (*599)
Example:, (*600)
<?php
use function _\curry;
$abc = function($a, $b, $c) {
return [$a, $b, $c];
};
$curried = curry($abc);
$curried(1)(2)(3);
// => [1, 2, 3]
$curried(1, 2)(3);
// => [1, 2, 3]
$curried(1, 2, 3);
// => [1, 2, 3]
// Curried with placeholders.
$curried(1)(_, 3)(2);
// => [1, 2, 3]
delay
Invokes func
after wait
milliseconds. Any additional arguments are
provided to func
when it's invoked., (*601)
Arguments:, (*602)
@param callable $func The function to delay., (*603)
@param int $wait The number of milliseconds to delay invocation., (*604)
@param array<int, mixed> $args, (*605)
Return:, (*606)
@return int the timer id., (*607)
Example:, (*608)
<?php
use function _\delay;
delay(function($text) {
echo $text;
}, 1000, 'later');
// => Echo 'later' after one second.
flip
Creates a function that invokes func
with arguments reversed., (*609)
Arguments:, (*610)
@param callable $func The function to flip arguments for., (*611)
Return:, (*612)
@return callable Returns the new flipped function., (*613)
Example:, (*614)
<?php
use function _\flip;
$flipped = flip(function() {
return func_get_args();
});
flipped('a', 'b', 'c', 'd');
// => ['d', 'c', 'b', 'a']
memoize
Creates a function that memoizes the result of func
. If resolver
is
provided, it determines the cache key for storing the result based on the
arguments provided to the memoized function. By default, the first argument
provided to the memoized function is used as the map cache key, (*615)
Note: The cache is exposed as the cache
property on the memoized
function. Its creation may be customized by replacing the _.memoize.Cache
constructor with one whose instances implement the
Map
method interface of clear
, delete
, get
, has
, and set
., (*616)
Arguments:, (*617)
@param callable $func The function to have its output memoized., (*618)
@param (callable | null) $resolver The function to resolve the cache key., (*619)
Return:, (*620)
@return callable Returns the new memoized function., (*621)
Example:, (*622)
<?php
use function _\memoize;
$object = ['a' => 1, 'b' => 2];
$other = ['c' => 3, 'd' => 4];
$values = memoize('_\values');
$values($object);
// => [1, 2]
$values($other);
// => [3, 4]
$object['a'] = 2;
$values($object);
// => [1, 2]
// Modify the result cache.
$values->cache->set($object, ['a', 'b']);
$values($object);
// => ['a', 'b']
negate
Creates a function that negates the result of the predicate func
, (*623)
Arguments:, (*624)
@param callable $predicate The predicate to negate., (*625)
Return:, (*626)
@return callable Returns the new negated function., (*627)
Example:, (*628)
<?php
use function _\negate;
function isEven($n) {
return $n % 2 == 0;
}
filter([1, 2, 3, 4, 5, 6], negate($isEven));
// => [1, 3, 5]
once
Creates a function that is restricted to invoking func
once. Repeat calls
to the function return the value of the first invocation. The func
is
invoked with the arguments of the created function., (*629)
Arguments:, (*630)
@param callable $func The function to restrict., (*631)
Return:, (*632)
@return callable the new restricted function., (*633)
Example:, (*634)
<?php
use function _\once;
$initialize = once('createApplication');
$initialize();
$initialize();
// => `createApplication` is invoked once
overArgs
Creates a function that invokes func
with its arguments transformed., (*635)
Arguments:, (*636)
@param callable $func The function to wrap., (*637)
@param callable[] $transforms The argument transforms., (*638)
Return:, (*639)
@return callable the new function., (*640)
Example:, (*641)
<?php
use function _\overArgs;
function doubled($n) {
return $n * 2;
}
function square($n) {
return $n * $n;
}
$func = overArgs(function($x, $y) {
return [$x, $y];
}, ['square', 'doubled']);
$func(9, 3);
// => [81, 6]
$func(10, 5);
// => [100, 10]
partial
Creates a function that invokes func
with partials
prepended to the
arguments it receives., (*642)
Arguments:, (*643)
@param callable $func The function to partially apply arguments to., (*644)
@param array<int, mixed> $partials The arguments to be partially applied., (*645)
Return:, (*646)
@return callable Returns the new partially applied function., (*647)
Example:, (*648)
<?php
use function _\partial;
function greet($greeting, $name) {
return $greeting . ' ' . $name;
}
$sayHelloTo = partial('greet', 'hello');
$sayHelloTo('fred');
// => 'hello fred'
rest
Creates a function that invokes func
with the this
binding of the
created function and arguments from start
and beyond provided as
an array., (*649)
Arguments:, (*650)
@param callable $func The function to apply a rest parameter to., (*651)
@param (int | null) $start The start position of the rest parameter., (*652)
Return:, (*653)
@return callable Returns the new function., (*654)
Example:, (*655)
<?php
use function _\rest;
$say = rest(function($what, $names) {
return $what . ' ' . implode(', ', initial($names)) .
(size($names) > 1 ? ', & ' : '') . last($names);
});
$say('hello', 'fred', 'barney', 'pebbles');
// => 'hello fred, barney, & pebbles'
spread
Creates a function that invokes func
with the this
binding of the
create function and an array of arguments much like
Function#apply
., (*656)
Note: This method is based on the
spread operator., (*657)
Arguments:, (*658)
@param callable $func The function to spread arguments over., (*659)
@param int $start The start position of the spread., (*660)
Return:, (*661)
@return callable Returns the new function., (*662)
Example:, (*663)
<?php
use function _\spread;
$say = spread(function($who, $what) {
return $who . ' says ' . $what;
});
$say(['fred', 'hello']);
// => 'fred says hello'
unary
Creates a function that accepts up to one argument, ignoring any
additional arguments., (*664)
Arguments:, (*665)
@param callable $func The function to cap arguments for., (*666)
Return:, (*667)
@return callable the new capped function., (*668)
Example:, (*669)
<?php
use function _\unary;
map(['6', '8', '10'], unary('intval'));
// => [6, 8, 10]
wrap
Creates a function that provides value
to wrapper
as its first
argument. Any additional arguments provided to the function are appended
to those provided to the wrapper
., (*670)
Arguments:, (*671)
@param mixed $value The value to wrap., (*672)
@param callable $wrapper The wrapper function., (*673)
Return:, (*674)
@return callable the new function., (*675)
Example:, (*676)
<?php
use function _\wrap;
$p = wrap('_\escape', function($func, $text) {
return '
' . $func($text) . ', (*677)
';
});
$p('fred, barney, & pebbles');
// => '
fred, barney, & pebbles, (*678)
'
Lang
eq
Performs a comparison between two values to determine if they are equivalent., (*679)
Arguments:, (*680)
@param mixed $value The value to compare., (*681)
@param mixed $other The other value to compare., (*682)
Return:, (*683)
@return boolean Returns true
if the values are equivalent, else false
., (*684)
Example:, (*685)
<?php
use function _\eq;
$object = (object) ['a' => 1];
$other = (object) ['a' => 1];
eq($object, $object);
// => true
eq($object, $other);
// => false
eq('a', 'a');
// => true
eq(['a'], (object) ['a']);
// => false
eq(INF, INF);
// => true
isEqual
Performs a deep comparison between two values to determine if they are
equivalent., (*686)
Note: This method supports comparing arrays, booleans,
DateTime objects, exception objects, SPLObjectStorage, numbers,
strings, typed arrays, resources, DOM Nodes. objects are compared
by their own, not inherited, enumerable properties., (*687)
Arguments:, (*688)
@param mixed $value The value to compare., (*689)
@param mixed $other The other value to compare., (*690)
Return:, (*691)
@return bool Returns true
if the values are equivalent, else false
., (*692)
Example:, (*693)
<?php
use function _\isEqual;
$object = [ 'a' => 1]
$other = ['a' => '1']
isEqual($object, $other)
// => true
$object === $other
// => false
isError
Checks if value
is an \Exception
, \ParseError
, \Error, \Throwable
, \SoapFault, \DOMException
, \PDOException`, object., (*694)
Arguments:, (*695)
@param mixed $value The value to check., (*696)
Return:, (*697)
@return boolean Returns true
if value
is an error object, else false
., (*698)
Example:, (*699)
<?php
use function _\isError;
isError(new \Exception())
// => true
isError(\Exception::Class)
// => false
Math
add
Adds two numbers., (*700)
Arguments:, (*701)
@param (int | float | string) $augend The first number in an addition., (*702)
@param (int | float | string) $addend The second number in an addition., (*703)
Return:, (*704)
@return (int | float) Returns the total., (*705)
Example:, (*706)
<?php
use function _\add;
add(6, 4);
// => 10
max
Computes the maximum value of array
. If array
is empty or falsey, null is returned., (*707)
Arguments:, (*708)
@param (array | null) $array The array to iterate over., (*709)
Return:, (*710)
@return (int | null) Returns the maximum value., (*711)
Example:, (*712)
<?php
use function _\max;
max([4, 2, 8, 6]);
// => 8
max([]);
// => null
maxBy
This method is like max
except that it accepts iteratee
which is
invoked for each element in array
to generate the criterion by which
the value is ranked. The iteratee is invoked with one argument: (value)., (*713)
Arguments:, (*714)
@param array $array The array to iterate over., (*715)
@param (callable | string) $iteratee The iteratee invoked per element., (*716)
Return:, (*717)
@return mixed Returns the maximum value., (*718)
Example:, (*719)
<?php
use function _\maxBy;
$objects = [['n' => 1], ['n' => 2]];
maxBy($objects, function($o) { return $o['n']; });
// => ['n' => 2]
// The `property` iteratee shorthand.
maxBy($objects, 'n');
// => ['n' => 2]
Number
clamp
Clamps number
within the inclusive lower
and upper
bounds., (*720)
Arguments:, (*721)
@param int $number The number to clamp., (*722)
@param int $lower The lower bound., (*723)
@param int $upper The upper bound., (*724)
Return:, (*725)
@return int Returns the clamped number., (*726)
Example:, (*727)
<?php
use function _\clamp;
clamp(-10, -5, 5)
// => -5
clamp(10, -5, 5)
// => 5
inRange
Checks if number
is between start
and up to, but not including, end
. If
end
is not specified, it's set to start
with start
then set to 0
.
If start
is greater than end
the params are swapped to support
negative ranges., (*728)
Arguments:, (*729)
@param float $number The number to check., (*730)
@param float $start The start of the range., (*731)
@param float $end The end of the range., (*732)
Return:, (*733)
@return boolean Returns true
if number
is in the range, else false
., (*734)
Example:, (*735)
<?php
use function _\inRange;
inRange(3, 2, 4)
// => true
inRange(4, 8)
// => true
inRange(4, 2)
// => false
inRange(2, 2)
// => false
inRange(1.2, 2)
// => true
inRange(5.2, 4)
// => false
inRange(-3, -2, -6)
// => true
random
Produces a random number between the inclusive lower
and upper
bounds.
If only one argument is provided a number between 0
and the given number
is returned. If floating
is true
, or either lower
or upper
are
floats, a floating-point number is returned instead of an integer., (*736)
Arguments:, (*737)
@param (int | float | bool) $lower The lower bound., (*738)
@param (int | float | bool) $upper The upper bound., (*739)
@param (bool | null) $floating Specify returning a floating-point number., (*740)
Return:, (*741)
@return (int | float) Returns the random number., (*742)
Example:, (*743)
<?php
use function _\random;
random(0, 5)
// => an integer between 0 and 5
random(5)
// => also an integer between 0 and 5
random(5, true)
// => a floating-point number between 0 and 5
random(1.2, 5.2)
// => a floating-point number between 1.2 and 5.2
Object
get
Gets the value at path of object. If the resolved value is null the defaultValue is returned in its place., (*744)
Arguments:, (*745)
@param mixed $object The associative array or object to fetch value from, (*746)
@param (array | string) $path Dot separated or array of string, (*747)
@param mixed $defaultValue (optional)The value returned for unresolved or null values., (*748)
Return:, (*749)
@return mixed Returns the resolved value., (*750)
Example:, (*751)
<?php
use function _\get;
$sampleArray = ["key1" => ["key2" => ["key3" => "val1", "key4" => ""]]];
get($sampleArray, 'key1.key2.key3');
// => "val1"
get($sampleArray, 'key1.key2.key5', "default");
// => "default"
get($sampleArray, 'key1.key2.key4', "default");
// => ""
pick
Creates an object composed of the picked object
properties., (*752)
Arguments:, (*753)
@param object $object The source object., (*754)
@param (string | string[]) $paths The property paths to pick., (*755)
Return:, (*756)
@return \stdClass Returns the new object., (*757)
Example:, (*758)
<?php
use function _\pick;
$object = (object) ['a' => 1, 'b' => '2', 'c' => 3];
pick($object, ['a', 'c']);
// => (object) ['a' => 1, 'c' => 3]
pickBy
Creates an object composed of the object
properties predicate
returns
truthy for. The predicate is invoked with two arguments: (value, key)., (*759)
Arguments:, (*760)
@param (object | null) $object The source object., (*761)
@param callable $predicate The function invoked per property., (*762)
Return:, (*763)
@return \stdClass Returns the new object., (*764)
Example:, (*765)
<?php
use function _\pickBy;
$object = (object) ['a' => 1, 'b' => 'abc', 'c' => 3];
pickBy(object, 'is_numeric');
// => (object) ['a' => 1, 'c' => 3]
Seq
chain
Creates a lodash
wrapper instance that wraps value
with explicit method
chain sequences enabled. The result of such sequences must be unwrapped
with ->value()
., (*766)
Arguments:, (*767)
@param mixed $value The value to wrap., (*768)
Return:, (*769)
@return _ Returns the new lodash
wrapper instance., (*770)
Example:, (*771)
<?php
use function _\chain;
$users = [
['user' => 'barney', 'age' => 36],
['user' => 'fred', 'age' => 40],
['user' => 'pebbles', 'age' => 1 ],
];
$youngest = chain($users)
->sortBy('age')
->map(function($o) {
return $o['user'] . ' is ' . $o['age'];
})
->head()
->value();
// => 'pebbles is 1'
String
camelCase
Converts string
to camel case., (*772)
Arguments:, (*773)
@param string $string The string to convert., (*774)
Return:, (*775)
@return string Returns the camel cased string., (*776)
Example:, (*777)
<?php
use function _\camelCase;
camelCase('Foo Bar')
// => 'fooBar'
camelCase('--foo-bar--')
// => 'fooBar'
camelCase('__FOO_BAR__')
// => 'fooBar'
capitalize
Converts the first character of string
to upper case and the remaining
to lower case., (*778)
Arguments:, (*779)
@param string $string The string to capitalize., (*780)
Return:, (*781)
@return string Returns the capitalized string., (*782)
Example:, (*783)
<?php
use function _\capitalize;
capitalize('FRED')
// => 'Fred'
deburr
Deburrs string
by converting
[Latin-1 Supplement](https =>//en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
and [Latin Extended-A](https =>//en.wikipedia.org/wiki/Latin_Extended-A)
letters to basic Latin letters and removing
[combining diacritical marks](https =>//en.wikipedia.org/wiki/Combining_Diacritical_Marks)., (*784)
Arguments:, (*785)
@param string $string The string to deburr., (*786)
Return:, (*787)
@return string Returns the deburred string., (*788)
Example:, (*789)
<?php
use function _\deburr;
deburr('déjà vu')
// => 'deja vu'
endsWith
Checks if string
ends with the given target string., (*790)
Arguments:, (*791)
@param string $string The string to inspect., (*792)
@param string $target The string to search for., (*793)
@param int $position The position to search up to., (*794)
Return:, (*795)
@return boolean Returns true
if string
ends with target
, else false
., (*796)
Example:, (*797)
<?php
use function _\endsWith;
endsWith('abc', 'c')
// => true
endsWith('abc', 'b')
// => false
endsWith('abc', 'b', 2)
// => true
escape
Converts the characters "&", "<", ">", '"', and "'" in string
to their
corresponding HTML entities., (*798)
Though the ">" character is escaped for symmetry, characters like
">" and "/" don't need escaping in HTML and have no special meaning
unless they're part of a tag or unquoted attribute value. See
Mathias Bynens's article
(under "semi-related fun fact") for more details., (*799)
When working with HTML you should always
quote attribute values to reduce
XSS vectors., (*800)
Arguments:, (*801)
@param string $string The string to escape., (*802)
Return:, (*803)
@return string Returns the escaped string., (*804)
Example:, (*805)
<?php
use function _\escape;
escape('fred, barney, & pebbles')
// => 'fred, barney, & pebbles'
escapeRegExp
Escapes the RegExp
special characters "^", "$", "\", ".", "*", "+",
"?", "(", ")", "[", "]", "{", "}", and "|" in string
., (*806)
Arguments:, (*807)
@param string $string The string to escape., (*808)
Return:, (*809)
@return string Returns the escaped string., (*810)
Example:, (*811)
<?php
use function _\escapeRegExp;
escapeRegExp('[lodash](https://lodash.com/)')
// => '\[lodash\]\(https://lodash\.com/\)'
kebabCase
Converts string
to
kebab case., (*812)
Arguments:, (*813)
@param string $string The string to convert., (*814)
Return:, (*815)
@return string Returns the kebab cased string., (*816)
Example:, (*817)
<?php
use function _\kebabCase;
kebabCase('Foo Bar')
// => 'foo-bar'
kebabCase('fooBar')
// => 'foo-bar'
kebabCase('__FOO_BAR__')
// => 'foo-bar'
lowerCase
Converts string
, as space separated words, to lower case., (*818)
Arguments:, (*819)
@param string $string The string to convert., (*820)
Return:, (*821)
@return string Returns the lower cased string., (*822)
Example:, (*823)
<?php
use function _\lowerCase;
lowerCase('--Foo-Bar--')
// => 'foo bar'
lowerCase('fooBar')
// => 'foo bar'
lowerCase('__FOO_BAR__')
// => 'foo bar'
lowerFirst
Converts the first character of string
to lower case., (*824)
Arguments:, (*825)
@param string $string The string to convert., (*826)
Return:, (*827)
@return string Returns the converted string., (*828)
Example:, (*829)
<?php
use function _\lowerFirst;
lowerFirst('Fred')
// => 'fred'
lowerFirst('FRED')
// => 'fRED'
pad
Pads string
on the left and right sides if it's shorter than length
.
Padding characters are truncated if they can't be evenly divided by length
., (*830)
Arguments:, (*831)
@param string $string The string to pad., (*832)
@param int $length The padding length., (*833)
@param string $chars The string used as padding., (*834)
Return:, (*835)
@return string Returns the padded string., (*836)
Example:, (*837)
<?php
use function _\pad;
pad('abc', 8)
// => ' abc '
pad('abc', 8, '_-')
// => '_-abc_-_'
pad('abc', 2)
// => 'abc'
padEnd
Pads string
on the right side if it's shorter than length
. Padding
characters are truncated if they exceed length
., (*838)
Arguments:, (*839)
@param string $string The string to pad., (*840)
@param int $length The padding length., (*841)
@param string $chars The string used as padding., (*842)
Return:, (*843)
@return string Returns the padded string., (*844)
Example:, (*845)
<?php
use function _\padEnd;
padEnd('abc', 6)
// => 'abc '
padEnd('abc', 6, '_-')
// => 'abc_-_'
padEnd('abc', 2)
// => 'abc'
padStart
Pads string
on the left side if it's shorter than length
. Padding
characters are truncated if they exceed length
., (*846)
s
Arguments:, (*847)
@param string $string ='' The string to pad., (*848)
@param int $length The padding length., (*849)
@param string $chars The string used as padding., (*850)
Return:, (*851)
@return string Returns the padded string., (*852)
Example:, (*853)
<?php
use function _\padStart;
padStart('abc', 6)
// => ' abc'
padStart('abc', 6, '_-')
// => '_-_abc'
padStart('abc', 2)
// => 'abc'
parseInt
Converts string
to an integer of the specified radix. If radix
is
undefined
or 0
, a radix
of 10
is used unless string
is a
hexadecimal, in which case a radix
of 16
is used., (*854)
Note: This method uses PHP's built-in integer casting, which does not necessarily align with the
ES5 implementation of parseInt
., (*855)
Arguments:, (*856)
@param (int | float | string) $string The string to convert., (*857)
@param int $radix The radix to interpret string
by., (*858)
Return:, (*859)
@return int Returns the converted integer., (*860)
Example:, (*861)
<?php
use function _\parseInt;
parseInt('08')
// => 8
repeat
Repeats the given string n
times., (*862)
Arguments:, (*863)
@param string $string The string to repeat., (*864)
@param int $n The number of times to repeat the string., (*865)
Return:, (*866)
@return string Returns the repeated string., (*867)
Example:, (*868)
<?php
use function _\repeat;
repeat('*', 3)
// => '***'
repeat('abc', 2)
// => 'abcabc'
repeat('abc', 0)
// => ''
replace
Replaces matches for pattern
in string
with replacement
., (*869)
Note: This method is based on
String#replace
., (*870)
Arguments:, (*871)
@param string $string The string to modify., (*872)
@param string $pattern The pattern to replace., (*873)
@param (callable | string) $replacement The match replacement., (*874)
Return:, (*875)
@return string Returns the modified string., (*876)
Example:, (*877)
<?php
use function _\replace;
replace('Hi Fred', 'Fred', 'Barney')
// => 'Hi Barney'
snakeCase
Converts string
to
snake case., (*878)
Arguments:, (*879)
@param string $string The string to convert., (*880)
Return:, (*881)
@return string Returns the snake cased string., (*882)
Example:, (*883)
<?php
use function _\snakeCase;
snakeCase('Foo Bar')
// => 'foo_bar'
snakeCase('fooBar')
// => 'foo_bar'
snakeCase('--FOO-BAR--')
// => 'foo_bar'
split
Splits string
by separator
., (*884)
Note: This method is based on
String#split
., (*885)
Arguments:, (*886)
@param string $string The string to split., (*887)
@param string $separator The separator pattern to split by., (*888)
@param int $limit The length to truncate results to., (*889)
Return:, (*890)
@return array Returns the string segments., (*891)
Example:, (*892)
<?php
use function _\split;
split('a-b-c', '-', 2)
// => ['a', 'b']
startCase
Converts string
to
start case., (*893)
Arguments:, (*894)
@param string $string The string to convert., (*895)
Return:, (*896)
@return string Returns the start cased string., (*897)
Example:, (*898)
<?php
use function _\startCase;
startCase('--foo-bar--')
// => 'Foo Bar'
startCase('fooBar')
// => 'Foo Bar'
startCase('__FOO_BAR__')
// => 'FOO BAR'
startsWith
Checks if string
starts with the given target string., (*899)
Arguments:, (*900)
@param string $string The string to inspect., (*901)
@param string $target The string to search for., (*902)
@param int $position The position to search from., (*903)
Return:, (*904)
@return boolean Returns true
if string
starts with target
, else false
., (*905)
Example:, (*906)
<?php
use function _\startsWith;
startsWith('abc', 'a')
// => true
startsWith('abc', 'b')
// => false
startsWith('abc', 'b', 1)
// => true
template
Creates a compiled template function that can interpolate data properties
in "interpolate" delimiters, HTML-escape interpolated data properties in
"escape" delimiters, and execute PHP in "evaluate" delimiters. Data
properties may be accessed as free variables in the template. If a setting
object is given, it takes precedence over $templateSettings
values., (*907)
RegExp $options['escape'] = _::$templateSettings['escape'] The HTML "escape" delimiter.
RegExp $options['evaluate'] = _::$templateSettings['evaluate'] The "evaluate" delimiter.
array $options['imports'] = _::$templateSettings['imports'] An object to import into the template as free variables.
RegExp $options['interpolate'] = _::$templateSettings['interpolate'] The "interpolate" delimiter., (*908)
Arguments:, (*909)
@param string $string The template string., (*910)
@param array $options The options array., (*911)
Return:, (*912)
@return callable Returns the compiled template function., (*913)
Example:, (*914)
<?php
use function _\template;
// Use the "interpolate" delimiter to create a compiled template.
$compiled = template('hello <%= user %>!')
$compiled([ 'user' => 'fred' ])
// => 'hello fred!'
// Use the HTML "escape" delimiter to escape data property values.
$compiled = template('<b><%- value %></b>')
$compiled([ 'value' => '<script>' ])
// => '<b><script></b>'
// Use the "evaluate" delimiter to execute JavaScript and generate HTML.
$compiled = template('<% foreach($users as $user) { %><li><%- user %></li><% }%>')
$compiled([ 'users' => ['fred', 'barney'] ])
// => '<li>fred</li><li>barney</li>'
// Use the internal `print` function in "evaluate" delimiters.
$compiled = template('<% print("hello " + $user)%>!')
$compiled([ 'user' => 'barney' ])
// => 'hello barney!'
// Use backslashes to treat delimiters as plain text.
$compiled = template('<%= "\\<%- value %\\>" %>')
$compiled([ 'value' => 'ignored' ])
// => '<%- value %>'
// Use the `imports` option to import functions or classes with aliases.
$text = '<% all($users, function($user) { %><li><%- user %></li><% })%>'
$compiled = template($text, { 'imports': { '_\each': 'all' } })
$compiled([ 'users' => ['fred', 'barney'] ])
// => '<li>fred</li><li>barney</li>'
// Use custom template delimiters.
\_::$templateSettings['interpolate'] = '{{([\s\S]+?)}}'
$compiled = template('hello {{ user }}!')
$compiled([ 'user' => 'mustache' ])
// => 'hello mustache!'
// Use the `source` property to access the compiled source of the template
template($mainText)->source;
toLower
Converts string
, as a whole, to lower case, (*915)
Arguments:, (*916)
@param string $string The string to convert., (*917)
Return:, (*918)
@return string Returns the lower cased string., (*919)
Example:, (*920)
<?php
use function _\toLower;
toLower('--Foo-Bar--')
// => '--foo-bar--'
toLower('fooBar')
// => 'foobar'
toLower('__FOO_BAR__')
// => '__foo_bar__'
toUpper
Converts string
, as a whole, to upper case, (*921)
Arguments:, (*922)
@param string $string The string to convert., (*923)
Return:, (*924)
@return string Returns the upper cased string., (*925)
Example:, (*926)
<?php
use function _\toUpper;
toUpper('--foo-bar--')
// => '--FOO-BAR--'
toUpper('fooBar')
// => 'FOOBAR'
toUpper('__foo_bar__')
// => '__FOO_BAR__'
trim
Removes leading and trailing whitespace or specified characters from string
., (*927)
Arguments:, (*928)
@param string $string The string to trim., (*929)
@param string $chars The characters to trim., (*930)
Return:, (*931)
@return string Returns the trimmed string., (*932)
Example:, (*933)
<?php
use function _\trim;
trim(' abc ')
// => 'abc'
trim('-_-abc-_-', '_-')
// => 'abc'
trimEnd
Removes trailing whitespace or specified characters from string
., (*934)
Arguments:, (*935)
@param string $string The string to trim., (*936)
@param string $chars The characters to trim., (*937)
Return:, (*938)
@return string Returns the trimmed string., (*939)
Example:, (*940)
<?php
use function _\trimEnd;
trimEnd(' abc ')
// => ' abc'
trimEnd('-_-abc-_-', '_-')
// => '-_-abc'
trimStart
Removes leading whitespace or specified characters from string
., (*941)
Arguments:, (*942)
@param string $string The string to trim., (*943)
@param string $chars The characters to trim., (*944)
Return:, (*945)
@return string Returns the trimmed string., (*946)
Example:, (*947)
<?php
use function _\trimStart;
trimStart(' abc ')
// => 'abc '
trimStart('-_-abc-_-', '_-')
// => 'abc-_-'
truncate
Truncates string
if it's longer than the given maximum string length.
The last characters of the truncated string are replaced with the omission
string which defaults to "..."., (*948)
length = 30 The maximum string length.
omission = '...' The string to indicate text is omitted.
separator The separator pattern to truncate to., (*949)
Arguments:, (*950)
@param string $string The string to truncate., (*951)
@param array $options The options object., (*952)
Return:, (*953)
@return string Returns the truncated string., (*954)
Example:, (*955)
<?php
use function _\truncate;
truncate('hi-diddly-ho there, neighborino')
// => 'hi-diddly-ho there, neighbo...'
truncate('hi-diddly-ho there, neighborino', [
'length' => 24,
'separator' => ' '
])
// => 'hi-diddly-ho there,...'
truncate('hi-diddly-ho there, neighborino', [
'length' => 24,
'separator' => '/,? +/'
])
// => 'hi-diddly-ho there...'
truncate('hi-diddly-ho there, neighborino', [
'omission' => ' [...]'
])
// => 'hi-diddly-ho there, neig [...]'
unescape
The inverse of escape
this method converts the HTML entities
&
, <
, >
, "
and '
in string
to
their corresponding characters., (*956)
Arguments:, (*957)
@param string $string The string to unescape., (*958)
Return:, (*959)
@return string Returns the unescaped string., (*960)
Example:, (*961)
<?php
use function _\unescape;
unescape('fred, barney, & pebbles')
// => 'fred, barney, & pebbles'
upperCase
Converts string
, as space separated words, to upper case., (*962)
Arguments:, (*963)
@param string $string The string to convert., (*964)
Return:, (*965)
@return string Returns the upper cased string.s, (*966)
Example:, (*967)
<?php
use function _\upperCase;
upperCase('--foo-bar')
// => 'FOO BAR'
upperCase('fooBar')
// => 'FOO BAR'
upperCase('__foo_bar__')
// => 'FOO BAR'
upperFirst
Converts the first character of string
to upper case., (*968)
Arguments:, (*969)
@param string $string The string to convert., (*970)
Return:, (*971)
@return string Returns the converted string., (*972)
Example:, (*973)
<?php
use function _\upperFirst;
upperFirst('fred')
// => 'Fred'
upperFirst('FRED')
// => 'FRED'
words
Splits string
into an array of its words., (*974)
Arguments:, (*975)
@param string $string The string to inspect., (*976)
@param string $pattern The pattern to match words., (*977)
Return:, (*978)
@return array Returns the words of string
., (*979)
Example:, (*980)
<?php
use function _\words;
words('fred, barney, & pebbles')
// => ['fred', 'barney', 'pebbles']
words('fred, barney, & pebbles', '/[^, ]+/g')
// => ['fred', 'barney', '&', 'pebbles']
Util
attempt
Attempts to invoke func
, returning either the result or the caught error
object. Any additional arguments are provided to func
when it's invoked., (*981)
s
Arguments:, (*982)
@param callable $func The function to attempt., (*983)
@param array<int, mixed> $args The arguments to invoke func
with., (*984)
Return:, (*985)
@return (mixed | \Throwable) Returns the func
result or error object., (*986)
Example:, (*987)
<?php
use function _\attempt;
// Avoid throwing errors for invalid PDO data source.
$elements = attempt(function () {
new \PDO(null);
});
if (isError($elements)) {
$elements = [];
}
defaultTo
Checks value to determine whether a default value should be returned in its place.
The defaultValue is returned if value is NaN or null., (*988)
Arguments:, (*989)
@param mixed $value Any value., (*990)
@param mixed $defaultValue Value to return when $value is null or NAN, (*991)
Return:, (*992)
@return mixed Returns value
., (*993)
Example:, (*994)
<?php
use function _\defaultTo;
$a = null;
defaultTo($a, "default");
// => "default"
$a = "x";
defaultTo($a, "default");
// => "x"
identity
This method returns the first argument it receives., (*995)
Arguments:, (*996)
@param mixed $value Any value., (*997)
Return:, (*998)
@return mixed Returns value
., (*999)
Example:, (*1000)
<?php
use function _\identity;
$object = ['a' => 1];
identity($object) === $object;
// => true
property
Creates a function that returns the value at path
of a given object., (*1001)
Arguments:, (*1002)
@param (array | string) $path The path of the property to get., (*1003)
Return:, (*1004)
@return callable Returns the new accessor function., (*1005)
Example:, (*1006)
<?php
use function _\property;
$objects = [
[ 'a' => [ 'b' => 2 ] ],
[ 'a' => [ 'b' => 1 ] ]
];
map($objects, property('a.b'));
// => [2, 1]
map(sortBy($objects, property(['a', 'b'])), 'a.b');
// => [1, 2]