spatie/piper
Pipe-operator-first PHP utility library for array and string manipulation. Piper ports many Laravel Collection and Str helpers to standalone functions that work with primitives, so you can compose readable pipelines for filtering, mapping, joining, and more.
title: Array functions
All array functions live in the Spatie\Piper\Arr namespace. Import them individually or in groups.
use function Spatie\Piper\Arr\{filter, map, values};
Each function takes its subject as the first argument, so it slots naturally into a pipe. The reference below lists every available function in alphabetical order. Click a name to jump straight to its description.
afterReturns the item after the given value.
[1, 2, 3] |> after(2); // 3
averageReturns the average of the given values.
[['score' => 10], ['score' => 20]] |> average('score'); // 15
avgAlias of average.
[['score' => 10], ['score' => 20]] |> avg('score'); // 15
beforeReturns the item before the given value.
[1, 2, 3] |> before(2); // 1
chunkBreaks the array into chunks of the given size.
[1, 2, 3, 4, 5] |> chunk(2); // [[1, 2], [3, 4], [5]]
chunkWhileBreaks the array into chunks while the callback returns true.
str_split('AABB') |> chunkWhile(fn (string $value, int $key, array $chunk) => $value === end($chunk)); // [['A', 'A'], ['B', 'B']]
collapseCollapses an array of arrays into a single array.
[[1, 2], [3, 4]] |> collapse(); // [1, 2, 3, 4]
collapseWithKeysCollapses an array of keyed arrays while preserving keys.
[['name' => 'Taylor'], ['role' => 'admin']] |> collapseWithKeys(); // ['name' => 'Taylor', 'role' => 'admin']
combineCombines the array values as keys with another set of values.
['name', 'role'] |> combine(['Taylor', 'admin']); // ['name' => 'Taylor', 'role' => 'admin']
concatAppends the given values to the end of the array.
[1, 2] |> concat([3, 4]); // [1, 2, 3, 4]
containsDetermines whether the array contains the given value or passes the given truth test.
['Taylor', 'Abigail'] |> contains('Taylor'); // true
containsStrictDetermines whether the array strictly contains the given value.
[1, 2, 3] |> containsStrict('1'); // false
countReturns the number of items in the array.
[1, 2, 3] |> count(); // 3
countByCounts values by the result of the given callback.
['laravel', 'php', 'piper'] |> countBy(fn (string $value) => strlen($value)); // [7 => 1, 3 => 1, 5 => 1]
crossJoinReturns the Cartesian product of the array and the given arrays.
[1, 2] |> crossJoin(['a', 'b']); // [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]
diffReturns the values that are not present in the given array.
['a', 'b', 'c'] |> diff(['b']); // [0 => 'a', 2 => 'c']
diffAssocReturns key/value pairs that are not present in the given array.
['a' => 1, 'b' => 2] |> diffAssoc(['a' => 1]); // ['b' => 2]
diffAssocUsingReturns key/value pairs that are not present after comparing keys with a callback.
['a' => 1, 'b' => 2] |> diffAssocUsing(['A' => 1], 'strcasecmp'); // ['b' => 2]
diffKeysReturns items whose keys are not present in the given array.
['a' => 1, 'b' => 2] |> diffKeys(['a' => 9]); // ['b' => 2]
diffKeysUsingReturns items whose keys are not present after comparing keys with a callback.
['a' => 1, 'b' => 2] |> diffKeysUsing(['A' => 9], 'strcasecmp'); // ['b' => 2]
diffUsingReturns values that are not present after comparing values with a callback.
['a', 'b'] |> diffUsing(['A'], 'strcasecmp'); // [1 => 'b']
doesntContainDetermines whether the array does not contain the given value or pass the given truth test.
['Taylor', 'Abigail'] |> doesntContain('Jess'); // true
doesntContainStrictDetermines whether the array does not strictly contain the given value.
[1, 2, 3] |> doesntContainStrict('1'); // true
dotFlattens a multidimensional array using dot notation.
['user' => ['name' => 'Taylor']] |> dot(); // ['user.name' => 'Taylor']
duplicatesReturns duplicate values from the array.
['a', 'b', 'a'] |> duplicates(); // [2 => 'a']
duplicatesStrictReturns duplicate values using strict comparisons.
[1, '1', 1] |> duplicatesStrict(); // [2 => 1]
eachIterates over each item in the array.
[1, 2, 3] |> each(fn (int $value) => logger($value));
eachSpreadIterates over nested item values by spreading them into the callback.
[[1, 2], [3, 4]] |> eachSpread(fn (int $a, int $b) => logger($a + $b));
ensureVerifies that every item in the array is of the expected type.
[1, 2, 3] |> ensure('int'); // [1, 2, 3]
everyDetermines whether all items pass the given truth test.
[1, 2, 3] |> every(fn (int $value) => $value > 0); // true
exceptReturns all items except those with the given keys.
['name' => 'Taylor', 'role' => 'admin'] |> except('role'); // ['name' => 'Taylor']
filterFilters the array using the given callback.
[1, 2, 3, 4] |> filter(fn (int $value) => $value > 2); // [2 => 3, 3 => 4]
firstReturns the first item that passes the given truth test.
[1, 2, 3] |> first(fn (int $value) => $value > 1); // 2
firstOrFailReturns the first item or throws when no item is found.
[1, 2, 3] |> firstOrFail(fn (int $value) => $value > 2); // 3
firstWhereReturns the first item matching the given key/value constraint.
[['score' => 98], ['score' => 91]] |> firstWhere('score', '>', 95); // ['score' => 98]
flatMapMaps over the array and flattens the result by one level.
[1, 2] |> flatMap(fn (int $value) => [$value, $value * 10]); // [1, 10, 2, 20]
flattenFlattens a multidimensional array.
[1, [2, [3]]] |> flatten(); // [1, 2, 3]
flipSwaps the array keys with their values.
['name' => 'Taylor'] |> flip(); // ['Taylor' => 'name']
forgetReturns a copy of the array without the given key.
['name' => 'Taylor', 'role' => 'admin'] |> forget('role'); // ['name' => 'Taylor']
forPageReturns the items that would appear on the given page.
[1, 2, 3, 4] |> forPage(2, 2); // [2 => 3, 3 => 4]
fromJsonDecodes a JSON string into an array.
fromJson('{"name":"Taylor"}'); // ['name' => 'Taylor']
getReturns the value for the given key, or a default value.
['name' => 'Taylor'] |> get('name'); // 'Taylor'
getOrPutReturns an existing value or evaluates and returns a default value.
['name' => 'Taylor'] |> getOrPut('role', 'admin'); // 'admin'
groupByGroups the array items by a given key or callback.
[['team' => 'core', 'name' => 'Taylor'], ['team' => 'docs', 'name' => 'Jess']] |> groupBy('team'); // ['core' => [...], 'docs' => [...]]
hasDetermines whether the given key exists in the array.
['name' => 'Taylor'] |> has('name'); // true
hasAnyDetermines whether any of the given keys exist in the array.
['name' => 'Taylor'] |> hasAny('email', 'name'); // true
hasManyDetermines whether more than one item passes the given truth test.
[1, 2, 3] |> hasMany(fn (int $value) => $value > 1); // true
hasSoleDetermines whether exactly one item passes the given truth test.
[1, 2, 3] |> hasSole(fn (int $value) => $value === 2); // true
implodeJoins array values into a string.
[['name' => 'Taylor'], ['name' => 'Abigail']] |> implode('name', ', '); // 'Taylor, Abigail'
intersectReturns the values that are present in the given array.
['a', 'b'] |> intersect(['b', 'c']); // [1 => 'b']
intersectAssocReturns key/value pairs that are present in the given array.
['a' => 1, 'b' => 2] |> intersectAssoc(['a' => 1]); // ['a' => 1]
intersectAssocUsingReturns key/value pairs that are present after comparing keys with a callback.
['a' => 1, 'b' => 2] |> intersectAssocUsing(['A' => 1], 'strcasecmp'); // ['a' => 1]
intersectByKeysReturns items whose keys are present in the given array.
['a' => 1, 'b' => 2] |> intersectByKeys(['b' => 9]); // ['b' => 2]
intersectUsingReturns values that are present after comparing values with a callback.
['a', 'b'] |> intersectUsing(['A'], 'strcasecmp'); // [0 => 'a']
isEmptyDetermines whether the array is empty.
[] |> isEmpty(); // true
isNotEmptyDetermines whether the array is not empty.
[1] |> isNotEmpty(); // true
joinJoins array values with a final glue string.
['a', 'b', 'c'] |> join(', ', ' and '); // 'a, b and c'
keyByKeys the array by the given key or callback.
[['id' => 1, 'name' => 'Taylor']] |> keyBy('id'); // [1 => ['id' => 1, 'name' => 'Taylor']]
keysReturns all keys from the array.
['name' => 'Taylor', 'role' => 'admin'] |> keys(); // ['name', 'role']
lastReturns the last item that passes the given truth test.
[1, 2, 3] |> last(fn (int $value) => $value < 3); // 2
makeConverts the given value into an array.
make('Taylor'); // ['Taylor']
mapMaps each item using the given callback.
[1, 2, 3] |> map(fn (int $value) => $value * 2); // [2, 4, 6]
mapIntoMaps each item into a new instance of the given class.
$users |> mapInto(UserData::class); // [UserData, UserData, ...]
mapSpreadMaps nested item values by spreading them into the callback.
[[1, 2], [3, 4]] |> mapSpread(fn (int $a, int $b) => $a + $b); // [3, 7]
mapToDictionaryGroups values returned by the callback into a dictionary.
$users |> mapToDictionary(fn (array $user) => [$user['team'] => $user['name']]); // ['core' => ['Taylor']]
mapToGroupsGroups values returned by the callback.
$users |> mapToGroups(fn (array $user) => [$user['team'] => $user['name']]); // ['core' => ['Taylor']]
mapWithKeysMaps items into key/value pairs.
$users |> mapWithKeys(fn (array $user) => [$user['email'] => $user['name']]); // ['taylor@example.com' => 'Taylor']
maxReturns the maximum value for a given key or callback.
[['score' => 10], ['score' => 20]] |> max('score'); // 20
medianReturns the median value for a given key.
[1, 1, 2, 4] |> median(); // 1.5
mergeMerges the given array into the current array.
['a'] |> merge(['b']); // ['a', 'b']
mergeRecursiveRecursively merges the given array into the current array.
['a' => ['x']] |> mergeRecursive(['a' => ['y']]); // ['a' => ['x', 'y']]
minReturns the minimum value for a given key or callback.
[['score' => 10], ['score' => 20]] |> min('score'); // 10
modeReturns the most frequently occurring value for a given key.
[1, 1, 2, 2, 3] |> mode(); // [1, 2]
multiplyCreates copies of the array items the given number of times.
['a', 'b'] |> multiply(2); // ['a', 'b', 'a', 'b']
nthReturns every nth item from the array.
[1, 2, 3, 4, 5] |> nth(2); // [1, 3, 5]
onlyReturns only the items with the given keys.
['name' => 'Taylor', 'role' => 'admin'] |> only('name'); // ['name' => 'Taylor']
padPads the array to the given size with a value.
[1, 2] |> pad(4, 0); // [1, 2, 0, 0]
partitionSeparates items that pass the truth test from those that do not.
[1, 2, 3, 4] |> partition(fn (int $value) => $value % 2 === 0); // [[1 => 2, 3 => 4], [0 => 1, 2 => 3]]
percentageReturns the percentage of items that pass the given truth test.
[1, 2, 3, 4] |> percentage(fn (int $value) => $value > 2); // 50.0
pluckRetrieves all values for a given key.
[['name' => 'Taylor'], ['name' => 'Abigail']] |> pluck('name'); // ['Taylor', 'Abigail']
popReturns and removes the last item from a copy of the array.
[1, 2, 3] |> pop(); // 3
prependAdds an item to the beginning of the array.
['b', 'c'] |> prepend('a'); // ['a', 'b', 'c']
pullReturns the value for a key from a copy of the array.
['name' => 'Taylor'] |> pull('name'); // 'Taylor'
pushAdds one or more items to the end of the array.
[1, 2] |> push(3, 4); // [1, 2, 3, 4]
putSets the given key and value on the array.
['name' => 'Taylor'] |> put('role', 'admin'); // ['name' => 'Taylor', 'role' => 'admin']
randomReturns one or more random items from the array.
['a', 'b', 'c'] |> random(); // 'b'
rangeCreates an array containing a range of numbers.
range(1, 3); // [1, 2, 3]
reduceReduces the array to a single value.
[1, 2, 3] |> reduce(fn (int $carry, int $value) => $carry + $value, 0); // 6
reduceSpreadReduces the array to multiple aggregate values.
[1, 2, 3] |> reduceSpread(fn (int $sum, int $count, int $value) => [$sum + $value, $count + 1], 0, 0); // [6, 3]
reduceWithKeysReduces the array to a single value while receiving keys.
['a' => 1, 'b' => 2] |> reduceWithKeys(fn (int $carry, int $value, string $key) => $carry + $value, 0); // 3
rejectFilters out items using the given callback.
[1, 2, 3, 4] |> reject(fn (int $value) => $value > 2); // [0 => 1, 1 => 2]
replaceReplaces items in the array with items from the given array.
['name' => 'Taylor'] |> replace(['name' => 'Abigail']); // ['name' => 'Abigail']
replaceRecursiveRecursively replaces items in the array with items from the given array.
['user' => ['name' => 'Taylor']] |> replaceRecursive(['user' => ['name' => 'Abigail']]); // ['user' => ['name' => 'Abigail']]
How can I help you explore Laravel packages today?