Lists
A list holds values in order: ['tea', 'milk', 'juice'], [3, 7, 9], or records such as [{ name: 'Ada', age: 36 }]. The first item is at index 0, and a negative index counts from the end, so $drinks[-1] is the last item.
List methods never change the list they are called on. A method such as ->push() or ->sort() gives a new list, so you keep the result in a variable or chain the next method onto it:
$drinks = ['tea', 'milk']
$more = $drinks->push('juice')
echo $drinks // ['tea', 'milk'] because ->push() gives a new list and leaves this one alone
echo $more // ['tea', 'milk', 'juice']
Methods that take a function call it once for each item. The function gets the item first and, if you ask for it, the item’s index second: fn(drink) => ... or fn(drink, index) => .... The hint in the editor shows what a method passes, such as ->reduce(fn(total, item), initial?). Where you only want a field or a method of each item, write it with a dot instead of a whole function: ->map(.name) is ->map(fn(person) => $person.name), and ->filter(.is_empty()) is ->filter(fn(text) => $text->is_empty()).
Find out about a list: count · count_of · is_empty · contains · index_of · any · all
Take items out: first · last · at · find · max · min · take · skip · slice · take_while · skip_while · pluck
Keep some items: filter · reject · only · without · partition · unique · difference · intersect · union
Change every item: map · flat_map · each
Add, remove and reorder: push · prepend · insert · replace_at · remove · remove_at · pop · reverse · sort · rotate
Combine into one value: sum · product · average · reduce · scan · join · common · count_by
Group and reshape: group_by · to_map · chunk · window · split · flatten · zip · cells · positions_of · shapes · combinations · permutations
->all()
->all(fn(item, index?)) is true when the function is true for every item. It stops at the first item that fails. An empty list gives true, because no item fails:
$scores = [72, 85, 91]
echo $scores->all(fn(score) => $score >= 50) // true because every score is at least 50
echo $scores->all(fn(score) => $score >= 80) // false because 72 is below 80
echo []->all(fn(score) => $score >= 80) // true because there is no score to fail
->any()
->any(fn(item, index?)?) is true when the function is true for at least one item. It stops at the first item that passes. Without a function it asks whether the list has any items at all:
$basket = ['apple', 'pear', 'fig']
echo $basket->any(fn(fruit) => $fruit->starts_with('p')) // true because pear starts with p
echo $basket->any(fn(fruit) => $fruit == 'kiwi') // false because no fruit is kiwi
echo $basket->any() // true because the basket isn't empty
->at()
->at(index) gives the item at a position, counting from 0. A negative index counts back from the end, so -1 is the last item. An index past either end gives null rather than an error. $list[index] reads the same item:
$week = ['mon', 'tue', 'wed']
echo $week->at(0) // 'mon' because positions start at 0
echo $week->at(-1) // 'wed' because -1 is the last item
echo $week->at(5) // null because there is no sixth item
->average()
->average(fn(item)?) adds the items up and divides by how many there are. Given a function, it averages what the function gives for each item. An empty list gives null, since there is nothing to average:
echo [4, 8, 9]->average() // 7 because 4 + 8 + 9 is 21, and 21 / 3 is 7
$orders = [{ total: 10 }, { total: 30 }]
echo $orders->average(.total) // 20 because 10 + 30 is 40, and 40 / 2 is 20
echo []->average() // null because there is nothing to average
->cells()
->cells(rows?, columns?, row:?, column:?) reads a list of lists, such as a ->grid(), like a table. On its own, or with rows, it gives every row; with columns it gives every column, top to bottom. row: picks one row and column: one column, each counted from 0 with -1 for the last, and the two together give the one cell where they meet. Rows may be different lengths: a column skips the rows too short to reach it.
$garden = ```text
#.#
..#
```
$plot = $garden->grid()
echo $plot->cells(rows) // [['#', '.', '#'], ['.', '.', '#']] because each line is a row
echo $plot->cells(columns) // [['#', '.'], ['.', '.'], ['#', '#']] because each column takes one character from every line
for column in $plot->cells(columns) {
echo $column->join('')
}
// '#.' then '..' then '##' because the loop goes through the columns left to right
echo $plot->cells(row: 0) // ['#', '.', '#'] because row 0 is the top line
echo $plot->cells(column: -1) // ['#', '#'] because -1 is the last column
echo $plot->cells(row: 1, column: 2) // '#' because row 1 is '..#' and column 2 is its last character
echo [[1, 2], [3, 4]]->cells(columns) // [[1, 3], [2, 4]] because any list of lists has columns too
->chunk()
->chunk(size) cuts the list into lists of size items, in order. The last list holds whatever is left, so it can be shorter:
$seats = ['ada', 'bo', 'cy', 'di', 'ed']
echo $seats->chunk(2) // [['ada', 'bo'], ['cy', 'di'], ['ed']] because 5 people fill two tables of 2 and leave 1
->combinations()
->combinations(size) gives every way to pick size items when the order of the picked items doesn’t matter. Each pick keeps the items in list order, and no item is picked twice in the same pick.
Picking 2 from ['tea', 'milk', 'juice'] works like this: pair tea with each item after it (milk, then juice), then pair milk with each item after it (juice). juice has nothing after it, so that’s all. ['milk', 'tea'] never appears, because it is the same pick as ['tea', 'milk']:
$drinks = ['tea', 'milk', 'juice']
echo $drinks->combinations(2) // [['tea', 'milk'], ['tea', 'juice'], ['milk', 'juice']] because 3 drinks give 3 ways to pick 2
echo $drinks->combinations(3) // [['tea', 'milk', 'juice']] because there is only one way to pick all 3
echo $drinks->combinations(4) // [] because you can't pick 4 from 3
A common use is checking every pair, such as finding the two prices that add up to a total:
$prices = [15, 40, 25, 60]
$pair = $prices->combinations(2)->find(fn(two) => $two->sum() == 65)
echo $pair // [40, 25] because 15 + 40, 15 + 25 and 15 + 60 aren't 65, but 40 + 25 is
The number of picks grows fast, so past a million lists it stops with a Limit error rather than run out of memory.
A function with one parameter per picked item gets them one by one, at any size: $prices->combinations(2)->count_of(fn(cheaper, dearer) => $cheaper + $dearer > 70) gets each pair as cheaper and dearer, and ->combinations(3) fills fn(first, second, third). It then doesn’t get the index.
->common()
->common(count?, least, by?) counts how often each item occurs and gives the items back in that order, each once. Without least the most common come first; with least the rarest do. count keeps that many from the front, and without it you get every distinct item. Items that occur equally often stay in the order they first appear, and each comes back as it is, so numbers stay numbers:
$basket = ['apple', 'pear', 'apple', 'fig', 'fig', 'apple']
// apple occurs 3 times, fig twice and pear once.
echo $basket->common() // ['apple', 'fig', 'pear'] because that is most to least
echo $basket->common(1) // ['apple'] because it is the 1st most common
echo $basket->common(1, least) // ['pear'] because it is the 1st least common
echo $basket->common(least) // ['pear', 'fig', 'apple'] because that is least to most
by: decides what counts as the same item. The item you get back is the first one of its kind:
$drinks = ['Tea', 'milk', 'tea']
echo $drinks->common(1, by: fn(drink) => $drink->lower()) // ['Tea'] because 'Tea' and 'tea' count as one drink, twice
->contains()
->contains(item) is true when the list has an item equal to the one given. It compares with ==, so the number 1 and the text '1' match:
$guests = ['ada', 'bo']
echo $guests->contains('bo') // true
echo $guests->contains('cy') // false
echo [1, 2, 3]->contains('2') // true because == finds '2' equal to 2
To ask whether any item passes a test rather than equals a value, use ->any().
->count()
->count() gives how many items the list has:
echo ['tea', 'milk', 'juice']->count() // 3
echo []->count() // 0
->count_by()
->count_by(fn(item)) groups the items by what the function gives for each, and counts each group. The result is a map from each answer to its count:
$words = ['apple', 'avocado', 'banana']
echo $words->count_by(fn(word) => $word->first()) // { a: 2, b: 1 } because two words start with a and one with b
->count_of()
->count_of(match) counts the items equal to a value (with ==), or, given a function, the items for which it is true:
$rolls = [6, 2, 6, 5, 6]
echo $rolls->count_of(6) // 3 because three rolls are 6
echo $rolls->count_of(fn(roll) => $roll > 4) // 4 because 6, 6, 5 and 6 are above 4
->difference()
->difference(other, by?) gives the items that aren’t in the other list, each once and in this list’s order. Items match with ==, or by what by: gives for each:
$invited = ['ada', 'bo', 'cy', 'di']
$replied = ['bo', 'di']
echo $invited->difference($replied) // ['ada', 'cy'] because bo and di have replied
->each()
->each(fn(item, index?)) calls the function for each item, for what it does rather than what it gives back, and returns the list unchanged so you can keep chaining. A function written with => holds one expression, so ->each() suits a call that does something, such as logging or saving each item:
$tasks = ['wash', 'dry', 'fold']
$same = $tasks->each(fn(task) => $log->info("Doing { $task }"))
// logs Doing wash, Doing dry and Doing fold
echo $same // ['wash', 'dry', 'fold'] because ->each() gives back the list it was called on
To run statements for each item, such as echo, write a for loop: for task at index in $tasks { echo "{ $index + 1 }. { $task }" }.
->filter()
->filter(fn(item, index?)) keeps the items for which the function is true, in order:
$scores = [72, 45, 91, 38]
echo $scores->filter(fn(score) => $score >= 50) // [72, 91] because 45 and 38 are below 50
$people = [{ name: 'Ada', active: true }, { name: 'Bo', active: false }]
echo $people->filter(.active)->pluck(name) // ['Ada'] because only Ada is active
->reject() keeps the others.
->find()
->find(fn(item, index?), last?) gives the first item for which the function is true, or with last, the last one. It gives null when no item passes:
$rolls = [2, 6, 3, 6, 1]
echo $rolls->find(fn(roll) => $roll > 4) // 6 because 6 is the first roll above 4
echo $rolls->find(fn(roll) => $roll < 3, last) // 1 because 1 is the last roll below 3
echo $rolls->find(fn(roll) => $roll > 6) // null because no roll is above 6
->first()
->first() gives the first item, or null for an empty list:
echo ['gold', 'silver', 'bronze']->first() // 'gold'
echo []->first() // null because there is no first item
->flat_map()
->flat_map(fn(item, index?)) is ->map() for a function that gives a list: each item’s list is spread into one flat list, rather than kept as a list of lists:
$lines = ['tea milk', 'juice']
echo $lines->map(fn(line) => $line->words()) // [['tea', 'milk'], ['juice']] because ->map() keeps each list
echo $lines->flat_map(fn(line) => $line->words()) // ['tea', 'milk', 'juice'] because ->flat_map() spreads them
->flatten()
->flatten() spreads the lists inside a list into it, one level deep. A list inside a list inside a list keeps its inner list:
echo [['tea', 'milk'], ['juice']]->flatten() // ['tea', 'milk', 'juice']
echo [[1, [2]], 3]->flatten() // [1, [2], 3] because only one level is spread
->group_by()
->group_by(fn(item)) puts the items into groups by what the function gives for each. The result is a map from each answer to the items that gave it, in order:
$words = ['tea', 'tap', 'milk']
echo $words->group_by(fn(word) => $word->first()) // { t: ['tea', 'tap'], m: ['milk'] } because tea and tap start with t
->count_by() gives how many are in each group instead.
->index_of()
->index_of(item, last?) gives the position of the first item equal to the one given (with ==), or of the first item for which a function is true. With last it looks from the end. It gives -1 when there is none:
$queue = ['ada', 'bo', 'cy', 'bo']
echo $queue->index_of('bo') // 1 because positions start at 0
echo $queue->index_of('bo', last) // 3 because the last bo is 4th
echo $queue->index_of(fn(name) => $name->count() > 2) // 0 because ada is the first name longer than 2
echo $queue->index_of('di') // -1 because di isn't in the queue
->insert()
->insert(index, item) gives a new list with the item put in at that position; the items from there on move along one. A negative index counts from the end, so -1 puts the item before the last one:
$week = ['mon', 'wed']
echo $week->insert(1, 'tue') // ['mon', 'tue', 'wed'] because tue goes in at position 1
->intersect()
->intersect(other, by?) gives the items that are in the other list too, each once and in this list’s order. Items match with ==, or by what by: gives for each:
$mine = ['tea', 'milk', 'juice']
$yours = ['juice', 'tea', 'cola']
echo $mine->intersect($yours) // ['tea', 'juice'] because both lists have tea and juice
$people = [{ id: 1, name: 'Ada' }, { id: 2, name: 'Bo' }]
echo $people->intersect([{ id: 2 }], by: .id)->pluck(name) // ['Bo'] because only Bo's id is in both
->is_empty()
->is_empty() is true when the list has no items:
echo []->is_empty() // true
echo ['tea']->is_empty() // false
->join()
->join(separator?) puts the items together into one text, with the separator between them, ', ' unless you give another:
$drinks = ['tea', 'milk', 'juice']
echo $drinks->join() // 'tea, milk, juice'
echo $drinks->join(' or ') // 'tea or milk or juice'
echo $drinks->join('') // 'teamilkjuice'
->last()
->last() gives the last item, or null for an empty list:
echo ['gold', 'silver', 'bronze']->last() // 'bronze'
echo []->last() // null
->map()
->map(fn(item, index?)) gives a new list with the function’s answer for each item, in the same order:
$prices = [2, 5, 10]
echo $prices->map(fn(price) => $price * 2) // [4, 10, 20] because each price is doubled
echo ['tea', 'milk']->map(.upper()) // ['TEA', 'MILK'] because .upper() calls ->upper() on each
echo ['tea', 'milk']->map(fn(drink, index) => "{ $index }:{ $drink }") // ['0:tea', '1:milk']
->max()
->max(by?) gives the largest item, or with by:, the item for which by: gives the largest value. It gives null for an empty list:
echo [72, 91, 45]->max() // 91
$players = [{ name: 'Ada', score: 72 }, { name: 'Bo', score: 91 }]
echo $players->max(by: .score).name // 'Bo' because Bo has the highest score
->min()
->min(by?) gives the smallest item, or with by:, the item for which by: gives the smallest value:
echo [72, 91, 45]->min() // 45
$shops = [{ name: 'corner', price: 3 }, { name: 'market', price: 2 }]
echo $shops->min(by: .price).name // 'market' because it is the cheapest
->numbers()
->numbers() gives every number in the list, in order. Numbers stay as they are, text gives the numbers written in it (as text’s ->numbers() does), and lists inside are read too. Anything else is skipped:
echo ['-3 4', 5]->numbers() // [-3, 4, 5] because the text holds -3 and 4
echo [[1, 2], 'and 3', true]->numbers() // [1, 2, 3] because true isn't a number
->only()
->only(what) keeps the items of one type, written as a bare word: ->only(number), ->only(string). On a list of a native type it also takes that type’s own filters, such as ->only(prereleases) on a semver[]:
$mixed = [3, 'tea', 7, true]
echo $mixed->only(number) // [3, 7] because only 3 and 7 are numbers
$versions: semver[] = ['1.2.0', '2.0.0-beta', '1.10.0']
echo $versions->only(prereleases) // ['2.0.0-beta'] because only that version has a -beta part
->without() keeps the others.
->partition()
->partition(fn(item, index?)) splits the list in two in one pass: the items for which the function is true, then the rest. It gives both as a list of two lists:
$numbers = [1, 2, 3, 4]
echo $numbers->partition(fn(number) => $number->is_even()) // [[2, 4], [1, 3]] because 2 and 4 are even
->permutations()
->permutations(size?) gives every ordering of the items. Unlike ->combinations(), order matters, so ['tea', 'milk'] and ['milk', 'tea'] are both there. Without size each ordering uses every item:
$drinks = ['tea', 'milk', 'juice']
echo $drinks->permutations()->count() // 6 because 3 choices for first, 2 for second and 1 for third
echo $drinks->permutations(2)->first() // ['tea', 'milk'] because orderings come in list order
echo ['tea', 'milk']->permutations() // [['tea', 'milk'], ['milk', 'tea']]
Past a million orderings it stops with a Limit error.
->pluck()
->pluck(key) gives one field from each item, in order. Given a list of keys, it gives a map of just those fields for each item. A missing field gives null:
$people = [{ name: 'Joan', age: 82 }, { name: 'Sam' }]
echo $people->pluck(name) // ['Joan', 'Sam']
echo $people->pluck([name, age]) // [{ name: 'Joan', age: 82 }, { name: 'Sam', age: null }] because Sam has no age
->pop()
->pop() gives a new list without its last item:
$stack = ['plate', 'bowl', 'cup']
echo $stack->pop() // ['plate', 'bowl'] because cup was on top
To read the last item, use ->last().
->positions_of()
->positions_of(item) gives every place an item is in a list of lists, such as a ->grid(), as points with a .row and a .column, row by row and left to right. Cells match with ==, or when a function given instead is true for them. Look a point up with ->contains({ row: ..., column: ... }):
$garden = ```text
#.#
..#
```
$trees = $garden->grid()->positions_of('#')
echo $trees // [{ row: 0, column: 0 }, { row: 0, column: 2 }, { row: 1, column: 2 }] because those are the three #s, top line first
echo $trees->contains({ row: 1, column: 2 }) // true because row 1 ends in #
echo $garden->grid()->positions_of(fn(cell) => $cell != '#')->count()
// 3 because three cells are not trees
With ->combinations(2), a function with two parameters gets each pair of points one by one. This counts the squares whose four corners are all trees:
$field = ```text
#.##.
.....
.#...
##.##
```
$trees = $field->grid()->positions_of('#')
echo $trees->combinations(2)->count_of(fn(left, right) {
// only two trees on the same row can be a square's top corners
if $left.row != $right.row {
return false
}
// the gap between them is the square's width, so the bottom corners sit that many rows down
$size = $right.column - $left.column
return $trees->contains({ row: $left.row + $size, column: $left.column })
and $trees->contains({ row: $left.row + $size, column: $right.column })
})
// 1 because only the trees at columns 0 and 3 of row 0 have trees 3 rows below both of them
->prepend()
->prepend(items...) gives a new list with the items put at the start, in the order given:
$queue = ['cy', 'di']
echo $queue->prepend('ada', 'bo') // ['ada', 'bo', 'cy', 'di']
->product()
->product(fn(item)?) multiplies the items together, as ->sum() adds them. Given a function, it multiplies what the function gives for each. An empty list gives 1. Whole numbers stay exact at any size:
echo [2, 3, 4]->product() // 24 because 2 * 3 * 4 is 24
$boxes = [{ width: 2 }, { width: 3 }]
echo $boxes->product(.width) // 6 because 2 * 3 is 6
echo []->product() // 1 because multiplying by nothing leaves 1
->push()
->push(items...) gives a new list with the items added at the end, in the order given:
$drinks = ['tea']
echo $drinks->push('milk', 'juice') // ['tea', 'milk', 'juice']
->reduce()
->reduce(fn(total, item), initial?) works through the list to make one value. The function gets the total so far and the next item, and gives the new total. With initial, that is the first total; without it, the first item is:
$basket = [3, 5, 2]
echo $basket->reduce(fn(total, price) => $total + $price) // 10 because 3, then 3 + 5, then 8 + 2
echo $basket->reduce(fn(total, price) => $total + $price, 100) // 110 because it starts from 100
echo $basket->reduce(fn(biggest, price) => $price > $biggest ? $price : $biggest) // 5
An empty list gives initial, or null without it. ->scan() keeps every total along the way.
->reject()
->reject(fn(item, index?)) keeps the items for which the function is false: the opposite of ->filter():
$scores = [72, 45, 91, 38]
echo $scores->reject(fn(score) => $score >= 50) // [45, 38] because those are the ones that aren't 50 or more
->remove()
->remove(item) gives a new list without any items equal to the one given (with ==):
echo ['tea', 'milk', 'tea']->remove('tea') // ['milk'] because every tea goes
->remove_at()
->remove_at(index) gives a new list without the item at that position. A negative index counts from the end:
$week = ['mon', 'tue', 'wed']
echo $week->remove_at(0) // ['tue', 'wed']
echo $week->remove_at(-1) // ['mon', 'tue'] because -1 is the last item
->replace_at()
->replace_at(index, item) gives a new list with the item at that position replaced. A negative index counts from the end, and an index past the end is an Argument error:
$order = ['tea', 'tae', 'milk']
echo $order->replace_at(1, 'juice') // ['tea', 'juice', 'milk'] because position 1 is replaced
->reverse()
->reverse() gives a new list with the items in the opposite order:
echo ['gold', 'silver', 'bronze']->reverse() // ['bronze', 'silver', 'gold']
->rotate()
->rotate(by) moves every item by places towards the start, and the items that fall off the front go on the end. A negative by turns the other way:
$week = ['mon', 'tue', 'wed', 'thu']
echo $week->rotate(1) // ['tue', 'wed', 'thu', 'mon'] because mon moves from the front to the end
echo $week->rotate(-1) // ['thu', 'mon', 'tue', 'wed'] because thu moves from the end to the front
echo $week->rotate(5) // ['tue', 'wed', 'thu', 'mon'] because 5 places round 4 items is 1 place
->scan()
->scan(fn(total, item), initial?) works like ->reduce() but keeps every total along the way, so you can see how the result builds up:
$spending = [5, 2, 8, 1]
echo $spending->scan(fn(total, amount) => $total + $amount) // [5, 7, 15, 16] because 5, then 5 + 2, then 7 + 8, then 15 + 1
echo $spending->scan(fn(total, amount) => $total - $amount, 20) // [15, 13, 5, 4] because a budget of 20 goes down by each amount
->shapes()
->shapes(mask?, square?, rectangle?, line?, circle?, of?, rotated?, size?, radius?, distance?) finds shapes in text, a list, a grid or a 3D list, and the built-in ones in a list of points { row, column } too. Text is read one row a line and one cell a character, so ->grid() isn’t needed first. A mask goes first, by name: a type that extends Mask, whose layout pictures the shape (or a list of them, [Block, Ell]). Every character of the layout matches itself, and symbols says what any other one matches, with any for a cell that isn’t part of the shape. For the built-in shapes, name one or several, and say which cells make them with of: (a value or a regex). Each match comes back once as { kind, points }: a square is a square, not also a rectangle. rotated turns a mask every way the input allows and lets the built-in shapes lean, a line needs size:, and a circle needs radius: and, optionally, distance: straight|steps|moves. Mask is also a type for parameters: fn count_in(input: string, shape: Mask) takes any mask.
$plot = ```text
@@@.
@..@
@@@@
```
echo $plot->shapes(square, of: '@')->count() // 1 because columns 0 and 2 of rows 0 and 2 are all @
echo $plot->shapes(square, rectangle, of: '@')->map(.kind) // ['square', 'rectangle', 'rectangle', 'rectangle'] because each match is counted once
echo $plot->shapes(line, of: '@', size: 4)->first().points->map(.column)
// [0, 1, 2, 3] because the bottom row is the only 4 @s in a row
type Corner extends Mask {
layout: ```text
@@
@.
```
symbols: { '.': any }
}
echo $plot->shapes(Corner, rotated)->count() // 3 because the L of three @s fits at three corners of the plot
->skip()
->skip(count) gives every item after the first count:
echo ['header', 'tea', 'milk']->skip(1) // ['tea', 'milk'] because the header line is skipped
->skip_while()
->skip_while(fn(item, index?)) skips items from the start for as long as the function is true, then keeps everything from the first item that fails, whatever comes after:
$lines = ['', '', 'tea', '', 'milk']
echo $lines->skip_while(.is_empty()) // ['tea', '', 'milk'] because only the blank lines at the start go
->slice()
->slice(start, end?) gives the items from position start up to, but not including, position end, or to the end of the list. Negative positions count from the end:
$letters = ['a', 'b', 'c', 'd', 'e']
echo $letters->slice(1, 3) // ['b', 'c'] because it stops before position 3
echo $letters->slice(-2) // ['d', 'e'] because -2 is the second to last
->sort()
->sort(compare?, by?, order?) gives a new list in order, smallest first. Text sorts alphabetically, ignoring case. by: gives what to sort each item on, order: desc puts the largest first, and compare: takes a function of two items that gives a negative number when the first should come first:
echo [3, 1, 2]->sort() // [1, 2, 3]
echo ['pear', 'Apple', 'fig']->sort() // ['Apple', 'fig', 'pear'] because case doesn't change the order
$people = [{ name: 'Bo', age: 9 }, { name: 'Ada', age: 36 }]
echo $people->sort(by: .age)->pluck(name) // ['Bo', 'Ada'] because 9 is less than 36
echo $people->sort(by: .age, order: desc)->pluck(name) // ['Ada', 'Bo']
echo [3, 1, 2]->sort(compare: fn(a, b) => $b - $a) // [3, 2, 1] because a larger b comes first
->split()
->split(separator) cuts the list into lists wherever the separator item appears, and drops the separator. Give a value to match with ==, or a check that is true for the separator. A separator at the start or the end leaves an empty list there:
$lines = ['tea', 'milk', '', 'juice']
echo $lines->split('') // [['tea', 'milk'], ['juice']] because '' is the separator
echo $lines->split(.is_empty()) // [['tea', 'milk'], ['juice']] because the check is true for ''
echo [5, 0, 7, 8, 0]->split(0) // [[5], [7, 8], []] because the 0 at the end leaves an empty list after it
->sum()
->sum(fn(item)?) adds the items up. Given a function, it adds what the function gives for each. An empty list gives 0. Whole numbers stay exact at any size:
echo [3, 5, 2]->sum() // 10
$basket = [{ item: 'tea', price: 3 }, { item: 'milk', price: 2 }]
echo $basket->sum(.price) // 5 because 3 + 2 is 5
echo []->sum() // 0
->take()
->take(count) gives the first count items, or all of them when there are fewer:
$podium = ['ada', 'bo', 'cy', 'di']
echo $podium->take(3) // ['ada', 'bo', 'cy']
echo $podium->take(9) // ['ada', 'bo', 'cy', 'di'] because there are only 4
->take_while()
->take_while(fn(item, index?)) keeps items from the start for as long as the function is true, and stops at the first that fails:
$temperatures = [12, 14, 17, 9, 18]
echo $temperatures->take_while(fn(degrees) => $degrees >= 10) // [12, 14, 17] because 9 stops it, even though 18 comes after
->to_map()
->to_map(fn(item)) makes a map with each item under the key the function gives for it. When two items give the same key, the later one wins:
$people = [{ id: 'a1', name: 'Ada' }, { id: 'b2', name: 'Bo' }]
$by_id = $people->to_map(.id)
echo $by_id.b2.name // 'Bo' because Bo is stored under b2
->union()
->union(other, by?) gives the items of both lists, each once: this list’s first, then the new ones from the other. Items match with ==, or by what by: gives for each:
$mine = ['tea', 'milk']
$yours = ['milk', 'juice']
echo $mine->union($yours) // ['tea', 'milk', 'juice'] because milk is only kept once
->unique()
->unique(by?) gives the list with each item once, keeping the first of any repeats. Items match with ===, so the number 1 and the text '1' are different. With by:, items match by what it gives:
echo [3, 1, 3, 2, 1]->unique() // [3, 1, 2]
$emails = ['ADA@x.com', 'bo@x.com', 'ada@x.com']
echo $emails->unique(by: .lower()) // ['ADA@x.com', 'bo@x.com'] because the two ada addresses match in lower case
->window()
->window(size, step?) gives every run of size items next to each other. Each run starts step items after the last one, 1 unless you give another, so the runs overlap:
$week = ['mon', 'tue', 'wed', 'thu']
echo $week->window(2) // [['mon', 'tue'], ['tue', 'wed'], ['wed', 'thu']] because each pair starts one day later
echo $week->window(2, 2) // [['mon', 'tue'], ['wed', 'thu']] because each pair starts two days later
->without()
->without(what) keeps the items that aren’t of a type, or, on a list of a native type, the ones its filter doesn’t keep. It is the opposite of ->only():
$mixed = [3, 'tea', 7, true]
echo $mixed->without(number) // ['tea', true] because 3 and 7 are numbers
$versions: semver[] = ['1.2.0', '2.0.0-beta', '1.10.0']
echo $versions->without(prereleases) // ['1.2.0', '1.10.0'] because 2.0.0-beta is a prerelease
->zip()
->zip(other) pairs each item with the item at the same position in the other list. It stops at the end of the shorter list:
$names = ['ada', 'bo']
$scores = [72, 91, 45]
echo $names->zip($scores) // [['ada', 72], ['bo', 91]] because 45 has no name to pair with