Tradotto automaticamente dall’inglese, che è la versione originale.
Campi e metodi di list
Liste come [1, 2, 3]. I metodi che modificano una lista restituiscono una nuova lista.
Una lista contiene valori in ordine: ['tea', 'milk', 'juice'], [3, 7, 9], oppure record come [{ name: 'Ada', age: 36 }]. Il primo elemento è all'indice 0, e un indice negativo conta dalla fine, quindi $drinks[-1] è l'ultimo elemento.
I metodi delle liste non modificano mai la lista su cui vengono chiamati. Un metodo come ->push() o ->sort() restituisce una nuova lista, quindi conserva il risultato in una variabile oppure concatena il metodo successivo:
<let name="drinks" value="['tea', 'milk']" />
<let name="more" value="$drinks->push('juice')" />
<echo value="$drinks" /> <!-- ['tea', 'milk'] because ->push() gives a new list and leaves this one alone -->
<echo value="$more" /> <!-- ['tea', 'milk', 'juice'] -->
$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']
I metodi che accettano una funzione la chiamano una volta per ogni elemento. La funzione riceve per prima l'elemento e, se lo chiedi, l'indice dell'elemento come secondo argomento: fn(drink) => ... o fn(drink, index) => .... Il suggerimento nell'editor mostra cosa passa un metodo, come ->reduce(fn(total, item), initial?). Quando vuoi solo un campo o un metodo di ogni elemento, scrivilo con un punto invece di una funzione intera: ->map(.name) equivale a ->map(fn(person) => $person.name), e ->filter(.is_empty()) equivale a ->filter(fn(text) => $text->is_empty()).
Un campo è un dato semplice sul valore, letto con un punto e senza parentesi: $value.name. Un metodo richiede argomenti o esegue un'operazione, e si chiama con ->: $value->name(arguments), oppure passando il valore con la pipe: $value |> name(arguments).
->all(fn(item, index?)) è vero quando la funzione è vera per ogni elemento. Si ferma al primo elemento che non la soddisfa. Una lista vuota restituisce true, perché nessun elemento fallisce:
<let name="scores" value="[72, 85, 91]" />
<echo value="$scores->all(fn(score) => $score >= 50)" /> <!-- true because every score is at least 50 -->
<echo value="$scores->all(fn(score) => $score >= 80)" /> <!-- false because 72 is below 80 -->
<echo value="[]->all(fn(score) => $score >= 80)" /> <!-- true because there is no score to fail -->
$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
Vero quando fn è vera per almeno un elemento (oppure, senza fn, se la lista non è vuota).
->any(fn(item, index?)?) è vero quando la funzione è vera per almeno un elemento. Si ferma al primo elemento che la soddisfa. Senza una funzione verifica soltanto se la lista ha almeno un elemento:
<let name="basket" value="['apple', 'pear', 'fig']" />
<echo value="$basket->any(fn(fruit) => $fruit->starts_with('p'))" /> <!-- true because pear starts with p -->
<echo value="$basket->any(fn(fruit) => $fruit == 'kiwi')" /> <!-- false because no fruit is kiwi -->
<echo value="$basket->any()" /> <!-- true because the basket isn't empty -->
$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
L'elemento a un indice; i valori negativi contano dalla fine.
->at(index) restituisce l'elemento in una posizione, contando da 0. Un indice negativo conta all'indietro dalla fine, quindi -1 è l'ultimo elemento. Un indice oltre uno dei due estremi restituisce null invece di un errore. $list[index] legge lo stesso elemento:
<let name="week" value="['mon', 'tue', 'wed']" />
<echo value="$week->at(0)" /> <!-- 'mon' because positions start at 0 -->
<echo value="$week->at(-1)" /> <!-- 'wed' because -1 is the last item -->
<echo value="$week->at(5)" /> <!-- null because there is no sixth 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
La media degli elementi (o di fn per ciascun elemento), oppure null se vuota.
->average(fn(item)?) somma gli elementi e divide per quanti sono. Con una funzione, calcola la media di ciò che la funzione restituisce per ogni elemento. Una lista vuota restituisce null, perché non c'è nulla da mediare:
<echo value="[4, 8, 9]->average()" /> <!-- 7 because 4 + 8 + 9 is 21, and 21 / 3 is 7 -->
<let name="orders" value="[{ total: 10 }, { total: 30 }]" />
<echo value="$orders->average(.total)" /> <!-- 20 because 10 + 30 is 40, and 40 / 2 is 20 -->
<echo value="[]->average()" /> <!-- null because 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
#list->cells(row?: number, rows?: bool, column?: number, columns?: bool)→ any
Le celle di una lista di liste, come un ->grid(). Da sola, o con rows, ogni riga; con columns, ogni colonna, dall'alto in basso. row: sceglie una riga e una colonna: una colonna, ciascuna contata da 0 (-1 è l'ultima). Una riga e una colonna insieme danno la sola cella in cui si incontrano. Le righe possono avere lunghezze diverse: una colonna salta le righe troppo corte per raggiungerla. 'ab\ncd'->grid()->cells(columns) è [['a', 'c'], ['b', 'd']].
->cells(rows?, columns?, row:?, column:?) legge una lista di liste, come un ->grid(), come una tabella. Da solo, o con rows, restituisce ogni riga; con columns restituisce ogni colonna, dall'alto in basso. row: sceglie una riga e column: una colonna, ciascuna contata da 0 con -1 per l'ultima, e le due insieme danno la sola cella in cui si incontrano. Le righe possono avere lunghezze diverse: una colonna salta le righe troppo corte per raggiungerla.
<let name="garden">```text
#.#
..#
```</let>
<let name="plot" value="$garden->grid()" />
<echo value="$plot->cells(rows)" /> <!-- [['#', '.', '#'], ['.', '.', '#']] because each line is a row -->
<echo value="$plot->cells(columns)" /> <!-- [['#', '.'], ['.', '.'], ['#', '#']] because each column takes one character from every line -->
<for each="column" in="$plot->cells(columns)">
<echo value="$column->join('')" />
</for>
<!-- '#.' then '..' then '##' because the loop goes through the columns left to right -->
<echo value="$plot->cells(row: 0)" /> <!-- ['#', '.', '#'] because row 0 is the top line -->
<echo value="$plot->cells(column: -1)" /> <!-- ['#', '#'] because -1 is the last column -->
<echo value="$plot->cells(row: 1, column: 2)" /> <!-- '#' because row 1 is '..#' and column 2 is its last character -->
<echo value="[[1, 2], [3, 4]]->cells(columns)" /> <!-- [[1, 3], [2, 4]] because any list of lists has columns too -->
$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(size) divide la lista in liste di size elementi, in ordine. L'ultima lista contiene ciò che resta, quindi può essere più corta:
<let name="seats" value="['ada', 'bo', 'cy', 'di', 'ed']" />
<echo value="$seats->chunk(2)" /> <!-- [['ada', 'bo'], ['cy', 'di'], ['ed']] because 5 people fill two tables of 2 and leave 1 -->
$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
Ogni modo di scegliere size elementi, senza considerare l'ordine, nell'ordine della lista: [1, 2, 3]->combinations(2) è [[1, 2], [1, 3], [2, 3]].
->combinations(size) restituisce ogni modo di scegliere size elementi quando l'ordine degli elementi scelti non conta. Ogni scelta mantiene gli elementi nell'ordine della lista, e nessun elemento viene scelto due volte nella stessa scelta.
Scegliere 2 da ['tea', 'milk', 'juice'] funziona così: abbina tea con ciascun elemento che lo segue (milk, poi juice), poi abbina milk con ciascun elemento che lo segue (juice). juice non ha nulla dopo di sé, quindi è tutto. ['milk', 'tea'] non compare mai, perché è la stessa scelta di ['tea', 'milk']:
<let name="drinks" value="['tea', 'milk', 'juice']" />
<echo value="$drinks->combinations(2)" /> <!-- [['tea', 'milk'], ['tea', 'juice'], ['milk', 'juice']] because 3 drinks give 3 ways to pick 2 -->
<echo value="$drinks->combinations(3)" /> <!-- [['tea', 'milk', 'juice']] because there is only one way to pick all 3 -->
<echo value="$drinks->combinations(4)" /> <!-- [] because you can't pick 4 from 3 -->
$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
Un uso comune è verificare ogni coppia, come trovare le due prezzi che sommati danno un totale:
<let name="prices" value="[15, 40, 25, 60]" />
<let name="pair" value="$prices->combinations(2)->find(fn(two) => $two->sum() == 65)" />
<echo value="$pair" /> <!-- [40, 25] because 15 + 40, 15 + 25 and 15 + 60 aren't 65, but 40 + 25 is -->
$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
Il numero di scelte cresce rapidamente, quindi oltre un milione di liste si ferma con un errore Limit invece di esaurire la memoria.
Una funzione con un parametro per ogni elemento scelto li riceve uno alla volta, di qualsiasi dimensione: $prices->combinations(2)->count_of(fn(cheaper, dearer) => $cheaper + $dearer > 70) riceve ogni coppia come cheaper e dearer, e ->combinations(3) riempie fn(first, second, third). Non riceve poi l'indice.
#list->common(count?: number, least?: bool, by?: fn(item))→ list
Gli elementi che compaiono più spesso, prima i più frequenti, ciascuno una sola volta e così come sono (i numeri restano numeri): [3, 7, 7, 9, 9, 9]->common(2) è [9, 7]. Con least vengono prima i più rari: ->common(1, least) è [3]. I pari merito mantengono l'ordine della lista. Senza count, ogni elemento diverso. Gli elementi si confrontano con ==, oppure tramite ciò che by: restituisce per ciascuno.
->common(count?, least, by?) conta quante volte compare ogni elemento e restituisce gli elementi in quell'ordine, ciascuno una sola volta. Senza least vengono prima i più comuni; con least vengono prima i più rari. count mantiene quel numero di elementi dall'inizio, e senza di esso ottieni ogni elemento diverso. Gli elementi che compaiono lo stesso numero di volte restano nell'ordine in cui compaiono per la prima volta, e ciascuno torna così com'è, quindi i numeri restano numeri:
<let name="basket" value="['apple', 'pear', 'apple', 'fig', 'fig', 'apple']" />
<!-- apple occurs 3 times, fig twice and pear once. -->
<echo value="$basket->common()" /> <!-- ['apple', 'fig', 'pear'] because that is most to least -->
<echo value="$basket->common(1)" /> <!-- ['apple'] because it is the 1st most common -->
<echo value="$basket->common(1, least)" /> <!-- ['pear'] because it is the 1st least common -->
<echo value="$basket->common(least)" /> <!-- ['pear', 'fig', 'apple'] because that is least to most -->
$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: decide cosa conta come lo stesso elemento. L'elemento restituito è il primo della sua specie:
<let name="drinks" value="['Tea', 'milk', 'tea']" />
<echo value="$drinks->common(1, by: fn(drink) => $drink->lower())" /> <!-- ['Tea'] because 'Tea' and 'tea' count as one drink, twice -->
$drinks = ['Tea', 'milk', 'tea']
echo $drinks->common(1, by: fn(drink) => $drink->lower()) // ['Tea'] because 'Tea' and 'tea' count as one drink, twice
->contains(item) è vero quando la lista contiene un elemento uguale a quello dato. Il confronto usa ==, quindi il numero 1 e il testo '1' corrispondono:
Una mappa dal risultato di fn a quanti elementi lo hanno prodotto: ['a', 'bb', 'cc']->count_by(->count()) è { 1: 1, 2: 2 }.
->count_by(fn(item)) raggruppa gli elementi in base a ciò che la funzione restituisce per ciascuno, e conta ogni gruppo. Il risultato è una mappa da ogni risposta al suo conteggio:
<let name="words" value="['apple', 'avocado', 'banana']" />
<echo value="$words->count_by(fn(word) => $word->first())" /> <!-- { a: 2, b: 1 } because two words start with a and one with b -->
$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
#list->difference(other: list, by?: fn(item))→ list
Gli elementi che non sono in other, ciascuno una sola volta e in ordine. Gli elementi si confrontano con ==, oppure tramite ciò che by: restituisce per ciascuno.
->difference(other, by?) restituisce gli elementi che non sono nell'altra lista, ciascuno una sola volta e nell'ordine di questa lista. Gli elementi si confrontano con ==, oppure tramite ciò che by: restituisce per ciascuno:
<let name="invited" value="['ada', 'bo', 'cy', 'di']" />
<let name="replied" value="['bo', 'di']" />
<echo value="$invited->difference($replied)" /> <!-- ['ada', 'cy'] because bo and di have replied -->
$invited = ['ada', 'bo', 'cy', 'di']
$replied = ['bo', 'di']
echo $invited->difference($replied) // ['ada', 'cy'] because bo and di have replied
Richiama fn per ogni elemento e restituisce la lista.
->each(fn(item, index?)) chiama la funzione per ogni elemento, per ciò che fa e non per ciò che restituisce, e restituisce la lista invariata così puoi continuare a concatenare. Una funzione scritta con => contiene una sola espressione, quindi ->each() è adatto a una chiamata che fa qualcosa, come registrare o salvare ogni elemento:
<let name="tasks" value="['wash', 'dry', 'fold']" />
<let name="same" value="$tasks->each(fn(task) => $log->info("Doing { $task }"))" />
<!-- logs Doing wash, Doing dry and Doing fold -->
<echo value="$same" /> <!-- ['wash', 'dry', 'fold'] because ->each() gives back the list it was called on -->
$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
Per eseguire istruzioni per ogni elemento, come echo, scrivi un ciclo for: for task at index in $tasks { echo "{ $index + 1 }. { $task }" }.
Il primo elemento per cui fn(item, index) è vero, o con last, l'ultimo; null se nessuno lo è.
->find(fn(item, index?), last?) restituisce il primo elemento per cui la funzione è vera, oppure, con last, l'ultimo. Restituisce null quando nessun elemento la supera:
<let name="rolls" value="[2, 6, 3, 6, 1]" />
<echo value="$rolls->find(fn(roll) => $roll > 4)" /> <!-- 6 because 6 is the first roll above 4 -->
<echo value="$rolls->find(fn(roll) => $roll < 3, last)" /> <!-- 1 because 1 is the last roll below 3 -->
<echo value="$rolls->find(fn(roll) => $roll > 6)" /> <!-- null because no roll is above 6 -->
$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
Applica una funzione a ogni elemento, poi appiattisce di un livello ogni lista di risultati.
->flat_map(fn(item, index?)) è ->map() per una funzione che restituisce una lista: la lista di ogni elemento viene distesa in un'unica lista piatta, invece di essere mantenuta come lista di liste:
<let name="lines" value="['tea milk', 'juice']" />
<echo value="$lines->map(fn(line) => $line->words())" /> <!-- [['tea', 'milk'], ['juice']] because ->map() keeps each list -->
<echo value="$lines->flat_map(fn(line) => $line->words())" /> <!-- ['tea', 'milk', 'juice'] because ->flat_map() spreads them -->
$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
Una mappa dal risultato di fn agli elementi che lo hanno prodotto.
->group_by(fn(item)) raggruppa gli elementi in base a ciò che la funzione restituisce per ciascuno. Il risultato è una mappa da ogni risposta agli elementi che l'hanno prodotta, in ordine:
<let name="words" value="['tea', 'tap', 'milk']" />
<echo value="$words->group_by(fn(word) => $word->first())" /> <!-- { t: ['tea', 'tap'], m: ['milk'] } because tea and tap start with t -->
$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() restituisce invece quanti elementi ci sono in ogni gruppo.
L'indice di un elemento (confrontato con ==), o del primo elemento per cui una fn(item, index) è vera; con last, l'ultimo. -1 se non esiste.
->index_of(item, last?) restituisce la posizione del primo elemento uguale a quello dato (con ==), oppure del primo elemento per cui una funzione è vera. Con last cerca dalla fine. Restituisce -1 quando non c'è:
<let name="queue" value="['ada', 'bo', 'cy', 'bo']" />
<echo value="$queue->index_of('bo')" /> <!-- 1 because positions start at 0 -->
<echo value="$queue->index_of('bo', last)" /> <!-- 3 because the last bo is 4th -->
<echo value="$queue->index_of(fn(name) => $name->count() > 2)" /> <!-- 0 because ada is the first name longer than 2 -->
<echo value="$queue->index_of('di')" /> <!-- -1 because di isn't in the queue -->
$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
Parametro
Accetta
itemobbligatorio
qualsiasi valore
lastfacoltativo
un flag: last oppure not last
Gli argomenti possono avere un nome: ->index_of(…, last: …).
Una nuova lista con item inserito all'indice index.
->insert(index, item) restituisce una nuova lista con l'elemento inserito in quella posizione; gli elementi da lì in poi si spostano di uno. Un indice negativo conta dalla fine, quindi -1 inserisce l'elemento prima dell'ultimo:
<let name="week" value="['mon', 'wed']" />
<echo value="$week->insert(1, 'tue')" /> <!-- ['mon', 'tue', 'wed'] because tue goes in at position 1 -->
$week = ['mon', 'wed']
echo $week->insert(1, 'tue') // ['mon', 'tue', 'wed'] because tue goes in at position 1
Gli argomenti possono avere un nome: ->insert(…, item: …).
Esempio
<echo>{ ['a', 'c']->insert(1, 'b') }</echo>
echo ['a', 'c']->insert(1, 'b')
#list->intersect(other: list, by?: fn(item))→ list
Gli elementi presenti anche in other, ciascuno una sola volta e nell'ordine originale. Gli elementi si confrontano con ==, oppure con ciò che by: restituisce per ciascuno.
->intersect(other, by?) restituisce gli elementi presenti anche nell'altra lista, ciascuno una sola volta e nell'ordine di questa lista. Gli elementi si confrontano con ==, oppure tramite ciò che by: restituisce per ciascuno:
<let name="mine" value="['tea', 'milk', 'juice']" />
<let name="yours" value="['juice', 'tea', 'cola']" />
<echo value="$mine->intersect($yours)" /> <!-- ['tea', 'juice'] because both lists have tea and juice -->
<let name="people" value="[{ id: 1, name: 'Ada' }, { id: 2, name: 'Bo' }]" />
<echo value="$people->intersect([{ id: 2 }], by: .id)->pluck(name)" /> <!-- ['Bo'] because only Bo's id is in both -->
$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
Ogni numero nella lista, in ordine: i numeri restano invariati, il testo fornisce i numeri che contiene, e vengono letti anche gli elenchi annidati, quindi ['-3 4', 5]->numbers() è [-3, 4, 5]. Gli altri elementi vengono ignorati.
->numbers() restituisce ogni numero della lista, in ordine. I numeri restano invariati, il testo fornisce i numeri scritti al suo interno (come fa ->numbers() del testo), e vengono letti anche gli elenchi annidati. Tutto il resto viene ignorato:
<echo value="['-3 4', 5]->numbers()" /> <!-- [-3, 4, 5] because the text holds -3 and 4 -->
<echo value="[[1, 2], 'and 3', true]->numbers()" /> <!-- [1, 2, 3] because true isn't a number -->
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
Gli elementi di un tipo (->only(semver), ->only(number)) o che un filtro sul tipo degli elementi mantiene (->only(releases) su un semver[]).
->only(what) mantiene gli elementi di un solo tipo, scritto come parola semplice: ->only(number), ->only(string). Su una lista di un tipo nativo accetta anche i filtri propri di quel tipo, come ->only(prereleases) su un semver[]:
<let name="mixed" value="[3, 'tea', 7, true]" />
<echo value="$mixed->only(number)" /> <!-- [3, 7] because only 3 and 7 are numbers -->
<let name="versions" type="semver[]" value="['1.2.0', '2.0.0-beta', '1.10.0']" />
<echo value="$versions->only(prereleases)" /> <!-- ['2.0.0-beta'] because only that version has a -beta part -->
$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
Restituisce [corrispondenti, rimanenti], verificando ogni elemento una sola volta.
->partition(fn(item, index?)) divide la lista in due in un solo passaggio: prima gli elementi per cui la funzione è vera, poi il resto. Restituisce entrambi come una lista di due liste:
<let name="numbers" value="[1, 2, 3, 4]" />
<echo value="$numbers->partition(fn(number) => $number->is_even())" /> <!-- [[2, 4], [1, 3]] because 2 and 4 are even -->
$numbers = [1, 2, 3, 4]
echo $numbers->partition(fn(number) => $number->is_even()) // [[2, 4], [1, 3]] because 2 and 4 are even
Ogni ordinamento degli elementi di size (tutti per impostazione predefinita), nell'ordine della lista: [1, 2, 3]->permutations(2) è [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]].
->permutations(size?) restituisce ogni ordinamento degli elementi. A differenza di ->combinations(), l'ordine conta, quindi sono presenti sia ['tea', 'milk'] che ['milk', 'tea']. Senza size ogni ordinamento usa tutti gli elementi:
<let name="drinks" value="['tea', 'milk', 'juice']" />
<echo value="$drinks->permutations()->count()" /> <!-- 6 because 3 choices for first, 2 for second and 1 for third -->
<echo value="$drinks->permutations(2)->first()" /> <!-- ['tea', 'milk'] because orderings come in list order -->
<echo value="['tea', 'milk']->permutations()" /> <!-- [['tea', 'milk'], ['milk', 'tea']] -->
$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']]
Oltre un milione di ordinamenti si interrompe con un errore Limit.
#list->pluck(key: Self.fields|Self.fields[])→ list
Un campo di ogni elemento, oppure una mappa dei campi selezionati per ogni elemento quando si passa una lista di chiavi.
->pluck(key) restituisce un campo da ogni elemento, in ordine. Con una lista di chiavi, restituisce per ogni elemento una mappa con solo quei campi. Un campo mancante dà null:
<let name="people" value="[{ name: 'Joan', age: 82 }, { name: 'Sam' }]" />
<echo value="$people->pluck(name)" /> <!-- ['Joan', 'Sam'] -->
<echo value="$people->pluck([name, age])" /> <!-- [{ name: 'Joan', age: 82 }, { name: 'Sam', age: null }] because Sam has no age -->
$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
Dove un elemento si trova in una lista di liste, come un ->grid(): ogni cella uguale ad esso (confrontata con ==), oppure per cui una fn(cella) è vera, come punto { row, column }, riga per riga e da sinistra a destra. '#.\n.#'->grid()->positions_of('#') è [{ row: 0, column: 0 }, { row: 1, column: 1 }]. Cerca un punto con ->contains({ row: 1, column: 1 }).
->positions_of(item) restituisce ogni posizione in cui un elemento si trova in una lista di liste, come una ->grid(), come punti con una .row e una .column, riga per riga e da sinistra a destra. Le celle corrispondono con ==, oppure quando una funzione passata al suo posto è vera per esse. Cerca un punto con ->contains({ row: ..., column: ... }):
<let name="garden">```text
#.#
..#
```</let>
<let name="trees" value="$garden->grid()->positions_of('#')" />
<echo value="$trees" /> <!-- [{ row: 0, column: 0 }, { row: 0, column: 2 }, { row: 1, column: 2 }] because those are the three #s, top line first -->
<echo value="$trees->contains({ row: 1, column: 2 })" /> <!-- true because row 1 ends in # -->
<echo value="$garden->grid()->positions_of(fn(cell) => $cell != '#')->count()" />
<!-- 3 because three cells are not trees -->
$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
Con ->combinations(2), una funzione con due parametri riceve ogni coppia di punti, una alla volta. Questo conta i quadrati i cui quattro angoli sono tutti alberi:
<let name="field">```text
#.##.
.....
.#...
##.##
```</let>
<let name="trees" value="$field->grid()->positions_of('#')" />
<echo value="$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 -->
$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
Gli elementi moltiplicati tra loro (oppure fn per ogni elemento); 1 per una lista vuota: [2, 3, 4]->product() è 24.
->product(fn(item)?) moltiplica tra loro gli elementi, come ->sum() li somma. Con una funzione, moltiplica ciò che la funzione restituisce per ciascuno. Una lista vuota dà 1. I numeri interi restano esatti a qualsiasi dimensione:
<echo value="[2, 3, 4]->product()" /> <!-- 24 because 2 * 3 * 4 is 24 -->
<let name="boxes" value="[{ width: 2 }, { width: 3 }]" />
<echo value="$boxes->product(.width)" /> <!-- 6 because 2 * 3 is 6 -->
<echo value="[]->product()" /> <!-- 1 because multiplying by nothing leaves 1 -->
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
Combina gli elementi in un unico valore: fn(totale, elemento) restituisce il totale successivo a partire dall'ultimo e dall'elemento successivo, partendo da initial: [1, 2, 3]->reduce(fn(totale, n) => $totale + $n, 10) è 16. Senza initial, il primo elemento è il primo totale, come fa ->scan(); una lista vuota dà allora null.
->reduce(fn(total, item), initial?) elabora la lista per ottenere un unico valore. La funzione riceve il totale parziale e l'elemento successivo, e restituisce il nuovo totale. Con initial, quello è il primo totale; senza, lo è il primo elemento:
<let name="basket" value="[3, 5, 2]" />
<echo value="$basket->reduce(fn(total, price) => $total + $price)" /> <!-- 10 because 3, then 3 + 5, then 8 + 2 -->
<echo value="$basket->reduce(fn(total, price) => $total + $price, 100)" /> <!-- 110 because it starts from 100 -->
<echo value="$basket->reduce(fn(biggest, price) => $price > $biggest ? $price : $biggest)" /> <!-- 5 -->
$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
Una lista vuota dà initial, oppure null senza di esso. ->scan() mantiene ogni totale intermedio.
->reject(fn(item, index?)) mantiene gli elementi per cui la funzione è falsa: l'opposto di ->filter():
<let name="scores" value="[72, 45, 91, 38]" />
<echo value="$scores->reject(fn(score) => $score >= 50)" /> <!-- [45, 38] because those are the ones that aren't 50 or more -->
$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
Una nuova lista con l'elemento all'indice sostituito; i valori negativi contano dalla fine.
->replace_at(index, item) restituisce una nuova lista con l'elemento in quella posizione sostituito. Un indice negativo conta dalla fine, e un indice oltre la fine è un errore Argument:
<let name="order" value="['tea', 'tae', 'milk']" />
<echo value="$order->replace_at(1, 'juice')" /> <!-- ['tea', 'juice', 'milk'] because position 1 is replaced -->
$order = ['tea', 'tae', 'milk']
echo $order->replace_at(1, 'juice') // ['tea', 'juice', 'milk'] because position 1 is replaced
Gli elementi vengono spostati di un certo numero di posizioni, con avvolgimento: [1, 2, 3, 4]->rotate(1) è [2, 3, 4, 1], e un by negativo li sposta nell'altra direzione, [1, 2, 3, 4]->rotate(-1) è [4, 1, 2, 3].
->rotate(by) sposta ogni elemento di by posizioni verso l'inizio, e gli elementi che escono dalla parte anteriore vanno in fondo. Un by negativo gira nell'altro senso:
<let name="week" value="['mon', 'tue', 'wed', 'thu']" />
<echo value="$week->rotate(1)" /> <!-- ['tue', 'wed', 'thu', 'mon'] because mon moves from the front to the end -->
<echo value="$week->rotate(-1)" /> <!-- ['thu', 'mon', 'tue', 'wed'] because thu moves from the end to the front -->
<echo value="$week->rotate(5)" /> <!-- ['tue', 'wed', 'thu', 'mon'] because 5 places round 4 items is 1 place -->
$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
Come ->reduce(), ma mantiene ogni totale parziale: [1, 2, 3]->scan(fn(total, n) => $total + $n) è [1, 3, 6]. Senza initial, il primo elemento fa da totale iniziale.
->scan(fn(total, item), initial?) funziona come ->reduce() ma mantiene ogni totale lungo il percorso, così puoi vedere come si costruisce il risultato:
<let name="spending" value="[5, 2, 8, 1]" />
<echo value="$spending->scan(fn(total, amount) => $total + $amount)" /> <!-- [5, 7, 15, 16] because 5, then 5 + 2, then 7 + 8, then 15 + 1 -->
<echo value="$spending->scan(fn(total, amount) => $total - $amount, 20)" /> <!-- [15, 13, 5, 4] because a budget of 20 goes down by each amount -->
$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
Every place a mask fits (->shapes(Tree), or ->shapes([Block, Ell]) for several), and every square, rectangle, line or circle (name one or several: ->shapes(square, circle, of: '#')) made by the cells that hold of: (a value, or a regex). It looks through text (each line a row, each character a cell, a blank line between layers), a list of values (one row), a grid ($grid[row][column]) or a 3D list ($cube[layer][row][column]); the built-in shapes also take a list of points { row, column }. A mask is a type that extends Mask: its layout is a picture, one character a cell, and each character matches a cell holding the same character, unless its symbols say otherwise (a value, a regex, a fn(cell), or any for a cell that isn't part of the shape). Each match is { kind, points }: kind is the mask's name or the shape, and each point is { row, column, value } (with symbol for a mask, and layer in 3D). With rotated, a mask is tried turned every way the input allows (back to front in a row, the four quarter turns in a grid, all 24 ways round in 3D), and squares, rectangles and lines may lean. A line needs size:, and a circle radius: and distance: straight (the default), steps or moves.
->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.
<let name="plot">```text
@@@.
@..@
@@@@
```</let>
<echo value="$plot->shapes(square, of: '@')->count()" /> <!-- 1 because columns 0 and 2 of rows 0 and 2 are all @ -->
<echo value="$plot->shapes(square, rectangle, of: '@')->map(.kind)" /> <!-- ['square', 'rectangle', 'rectangle', 'rectangle'] because each match is counted once -->
<echo value="$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 name="Corner" extends="Mask">
<field name="layout" default="```text
@@
@.
```" />
<field name="symbols" default="{ '.': any }" />
</type>
<echo value="$plot->shapes(Corner, rotated)->count()" /> <!-- 3 because the L of three @s fits at three corners of the plot -->
$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
Gli elementi dopo quelli iniziali per cui fn(item, index) è vero.
->skip_while(fn(item, index?)) salta gli elementi dall'inizio finché la funzione è vera, poi mantiene tutto a partire dal primo elemento che fallisce, qualunque cosa venga dopo:
<let name="lines" value="['', '', 'tea', '', 'milk']" />
<echo value="$lines->skip_while(.is_empty())" /> <!-- ['tea', '', 'milk'] because only the blank lines at the start go -->
$lines = ['', '', 'tea', '', 'milk']
echo $lines->skip_while(.is_empty()) // ['tea', '', 'milk'] because only the blank lines at the start go
Gli elementi da start fino a (escluso) end; le posizioni negative contano dalla fine.
->slice(start, end?) restituisce gli elementi dalla posizione start fino a, escludendola, la posizione end, oppure fino alla fine della lista. Le posizioni negative contano dalla fine:
<let name="letters" value="['a', 'b', 'c', 'd', 'e']" />
<echo value="$letters->slice(1, 3)" /> <!-- ['b', 'c'] because it stops before position 3 -->
<echo value="$letters->slice(-2)" /> <!-- ['d', 'e'] because -2 is the second to last -->
$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
#list->sort(compare?: fn(a, b), by?: fn(item), order?: asc|desc)→ list
Una copia ordinata: by: fn(item) fornisce la chiave su cui ordinare, ->sort(by: .name), e order: desc mette per primo il più grande. Una compare fn(a, b) restituisce un valore negativo, 0 o positivo.
->sort(compare?, by?, order?) restituisce una nuova lista in ordine, dal più piccolo. Il testo viene ordinato alfabeticamente, senza distinguere maiuscole e minuscole. by: indica su cosa ordinare ogni elemento, order: desc mette per primo il più grande, e compare: accetta una funzione di due elementi che restituisce un numero negativo quando il primo deve venire prima:
<echo value="[3, 1, 2]->sort()" /> <!-- [1, 2, 3] -->
<echo value="['pear', 'Apple', 'fig']->sort()" /> <!-- ['Apple', 'fig', 'pear'] because case doesn't change the order -->
<let name="people" value="[{ name: 'Bo', age: 9 }, { name: 'Ada', age: 36 }]" />
<echo value="$people->sort(by: .age)->pluck(name)" /> <!-- ['Bo', 'Ada'] because 9 is less than 36 -->
<echo value="$people->sort(by: .age, order: desc)->pluck(name)" /> <!-- ['Ada', 'Bo'] -->
<echo value="[3, 1, 2]->sort(compare: fn(a, b) => $b - $a)" /> <!-- [3, 2, 1] because a larger b comes 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
La lista divisa in liste ad ogni elemento separatore, che viene scartato: ['tea', 'milk', '', 'juice']->split('') è [['tea', 'milk'], ['juice']]. Il separatore è un valore (confrontato con ==) oppure un controllo come .is_empty() o fn(item). Separatori consecutivi, oppure all'inizio o alla fine, danno liste vuote.
->split(separator) divide la lista in liste ogni volta che compare l'elemento separatore, e scarta il separatore. Indica un valore da confrontare con ==, oppure un controllo che sia vero per il separatore. Un separatore all'inizio o alla fine lascia lì una lista vuota:
<let name="lines" value="['tea', 'milk', '', 'juice']" />
<echo value="$lines->split('')" /> <!-- [['tea', 'milk'], ['juice']] because '' is the separator -->
<echo value="$lines->split(.is_empty())" /> <!-- [['tea', 'milk'], ['juice']] because the check is true for '' -->
<echo value="[5, 0, 7, 8, 0]->split(0)" /> <!-- [[5], [7, 8], []] because the 0 at the end leaves an empty list after it -->
$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
Il totale degli elementi (o di fn per ogni elemento).
->sum(fn(item)?) somma gli elementi. Se viene data una funzione, somma quanto la funzione restituisce per ciascuno. Una lista vuota dà 0. I numeri interi restano esatti a qualsiasi dimensione:
Una mappa con fn(item) come chiave di ogni elemento.
->to_map(fn(item)) crea una mappa con ogni elemento sotto la chiave che la funzione gli assegna. Quando due elementi danno la stessa chiave, vince quello successivo:
<let name="people" value="[{ id: 'a1', name: 'Ada' }, { id: 'b2', name: 'Bo' }]" />
<let name="by_id" value="$people->to_map(.id)" />
<echo value="$by_id.b2.name" /> <!-- 'Bo' because Bo is stored under b2 -->
$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
Gli elementi di entrambe le liste, ciascuno una volta: prima quelli di questa lista, poi i nuovi da other. Gli elementi si confrontano con ==, oppure in base a ciò che by: restituisce per ciascuno.
->union(other, by?) restituisce gli elementi di entrambe le liste, ciascuno una volta: prima quelli di questa lista, poi i nuovi dall'altra. Gli elementi si confrontano con ==, oppure in base a ciò che by: restituisce per ciascuno:
<let name="mine" value="['tea', 'milk']" />
<let name="yours" value="['milk', 'juice']" />
<echo value="$mine->union($yours)" /> <!-- ['tea', 'milk', 'juice'] because milk is only kept once -->
$mine = ['tea', 'milk']
$yours = ['milk', 'juice']
echo $mine->union($yours) // ['tea', 'milk', 'juice'] because milk is only kept once
La lista senza duplicati, usando l'uguaglianza stretta (===), oppure mantenendo il primo elemento per ogni chiave by: fn(item, index): ->unique(by: .email).
->unique(by?) restituisce la lista con ogni elemento una sola volta, mantenendo il primo di eventuali ripetuti. Gli elementi si confrontano con ===, quindi il numero 1 e il testo '1' sono diversi. Con by:, gli elementi si confrontano in base a ciò che restituisce:
<echo value="[3, 1, 3, 2, 1]->unique()" /> <!-- [3, 1, 2] -->
<let name="emails" value="['ADA@x.com', 'bo@x.com', 'ada@x.com']" />
<echo value="$emails->unique(by: .lower())" /> <!-- ['ADA@x.com', 'bo@x.com'] because the two ada addresses match in lower case -->
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
Sequenze sovrapposte di elementi di dimensione size, ognuna che inizia step elementi dopo l'ultima (1 di default): [1, 2, 3]->window(2) è [[1, 2], [2, 3]].
->window(size, step?) restituisce ogni sequenza di size elementi affiancati. Ogni sequenza inizia step elementi dopo l'ultimo, 1 se non ne indichi un altro, quindi le sequenze si sovrappongono:
<let name="week" value="['mon', 'tue', 'wed', 'thu']" />
<echo value="$week->window(2)" /> <!-- [['mon', 'tue'], ['tue', 'wed'], ['wed', 'thu']] because each pair starts one day later -->
<echo value="$week->window(2, 2)" /> <!-- [['mon', 'tue'], ['wed', 'thu']] because each pair starts two days later -->
$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
Gli elementi che non sono di un tipo (->without(string)), oppure senza quelli che un filtro sul tipo degli elementi mantiene (->without(prereleases)).
->without(what) mantiene gli elementi che non sono di un tipo oppure, su una lista di un tipo nativo, quelli che il suo filtro non mantiene. È l'opposto di ->only():
<let name="mixed" value="[3, 'tea', 7, true]" />
<echo value="$mixed->without(number)" /> <!-- ['tea', true] because 3 and 7 are numbers -->
<let name="versions" type="semver[]" value="['1.2.0', '2.0.0-beta', '1.10.0']" />
<echo value="$versions->without(prereleases)" /> <!-- ['1.2.0', '1.10.0'] because 2.0.0-beta is a prerelease -->
$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
Coppie di elementi di entrambe le liste: [[a1, b1], [a2, b2]...].
->zip(other) abbina ogni elemento con l'elemento nella stessa posizione dell'altra lista. Si ferma alla fine della lista più corta:
<let name="names" value="['ada', 'bo']" />
<let name="scores" value="[72, 91, 45]" />
<echo value="$names->zip($scores)" /> <!-- [['ada', 72], ['bo', 91]] because 45 has no name to pair with -->
$names = ['ada', 'bo']
$scores = [72, 91, 45]
echo $names->zip($scores) // [['ada', 72], ['bo', 91]] because 45 has no name to pair with