Maps

A map holds values under names, called keys: { name: 'Ada', age: 36 }. Read a value with a dot, $person.name, or with brackets when the key is in a variable or has a space in it, $person['home town']. Keys are text and keep the order you wrote them in.

Map methods never change the map they are called on. A method such as ->set() or ->remove() gives a new map, so you keep the result or chain the next method onto it:

$stock = { apples: 3 }
$more = $stock->set('pears', 5)
echo $stock->count()   // 1 because ->set() gives a new map and leaves this one alone
echo $more->count()    // 2 because the new map has apples and pears

Methods that take a function call it once for each entry. The function gets the value first and, if you ask for it, the key second: fn(count) => ... or fn(count, fruit) => .... ->map_keys() is the one exception, since it is about keys: it passes the key first. Where you only want a field or a method of each value, write it with a dot instead of a whole function: ->filter(.is_active) is ->filter(fn(user) => $user.is_active).

Find out about a map: count · is_empty · has · get · any · all · find

Take it apart: keys · values · entries

Keep some entries: filter · reject · pick · omit

Change it: set · remove · merge · deep_merge · map · map_keys · sort

Combine into one value: reduce

->all()

->all(fn(value, key?)) is true when the function is true for every entry. It stops at the first entry that fails. An empty map gives true, because no entry fails:

$stock = { apples: 3, pears: 0, plums: 2 }
echo $stock->all(fn(count) => $count >= 0)   // true because no count is below zero
echo $stock->all(fn(count) => $count > 0)    // false because there are no pears left
echo {}->all(fn(count) => $count > 0)        // true because there is no entry to fail

->any()

->any(fn(value, key?)) is true when the function is true for at least one entry. It stops at the first entry that passes:

$stock = { apples: 3, pears: 0, plums: 2 }
echo $stock->any(fn(count) => $count == 0)                // true because pears have run out
echo $stock->any(fn(count, fruit) => $fruit == 'kiwis')   // false because there is no kiwis key

->count()

->count() is how many keys the map has. A key whose value is null still counts, because the key is there:

echo { apples: 3, pears: 0 }->count()          // 2 because there are two keys
echo { name: 'Ada', nickname: null }->count()  // 2 because nickname is a key, even with no value
echo {}->count()                               // 0

->deep_merge()

->deep_merge(other) adds another map’s keys, as ->merge() does, but goes inside maps that both have under the same key and merges those too. Anything that isn’t a map on both sides, such as a list, a number or null, is replaced by the other map’s value. It suits settings, where a small override changes one setting deep inside without losing the rest:

$defaults = { theme: { colour: 'blue', size: 12 }, tags: ['news'] }
$mine = { theme: { size: 14 }, tags: ['sport'] }
$settings = $defaults->deep_merge($mine)
echo $settings.theme   // { colour: 'blue', size: 14 } because both themes are maps, so only size changes
echo $settings.tags    // ['sport'] because lists aren't merged: the new list replaces the old one
echo $defaults->merge($mine).theme   // { size: 14 } because ->merge() replaces the whole theme

->entries()

->entries() turns the map into a list of { key, value } maps, in order. Use it when you need list methods that a map doesn’t have, such as ->take() or ->join():

$prices = { tea: 2, cake: 3 }
echo $prices->entries()   // [{ key: 'tea', value: 2 }, { key: 'cake', value: 3 }]
$menu = $prices->entries()->map(fn(entry) => "{ $entry.key }: £{ $entry.value }")
echo $menu->join(', ')    // 'tea: £2, cake: £3'

->filter()

->filter(fn(value, key?)) keeps the entries for which the function is true, in their order. ->reject() keeps the others:

$stock = { apples: 3, pears: 0, plums: 2 }
echo $stock->filter(fn(count) => $count > 0)                     // { apples: 3, plums: 2 } because pears are at 0
echo $stock->filter(fn(count, fruit) => $fruit->starts_with('p')) // { pears: 0, plums: 2 } because the key is checked this time

->find()

->find(fn(value, key?)) gives the first entry for which the function is true, as a { key, value } map, so you know which key it was. It gives null when no entry passes:

$stock = { apples: 3, pears: 0, plums: 0 }
echo $stock->find(fn(count) => $count == 0)       // { key: 'pears', value: 0 } because pears come before plums
echo $stock->find(fn(count) => $count == 0).key   // 'pears'
echo $stock->find(fn(count) => $count > 10)       // null because nothing has more than 10

->get()

->get(key, default?) reads the value for a key, or gives the default when the key isn’t there (null if you give none). Use it for a key held in a variable, or where a missing key is normal:

$person = { name: 'Ada', age: 36 }
echo $person->get('name')           // 'Ada'
echo $person->get('town', 'Leeds')  // 'Leeds' because there is no town key
echo $person->get('town')           // null because there is no town key and no default

->has()

->has(key) is true when the map has the key, even if its value is null. Keys match exactly, so capital letters count:

$person = { name: 'Ada', nickname: null }
echo $person->has('name')      // true
echo $person->has('nickname')  // true because the key is there, even with no value
echo $person->has('Name')      // false because keys match exactly, and this one is name

->is_empty()

->is_empty() is true when the map has no keys at all:

echo {}->is_empty()            // true
echo { cart: [] }->is_empty()  // false because the map has a key, even though its list is empty

->keys()

->keys() gives the keys as a list, in order:

$scores = { ada: 12, bo: 9 }
echo $scores->keys()                // ['ada', 'bo']
echo $scores->keys()->join(' and ') // 'ada and bo'

->map()

->map(fn(value, key?)) gives a map with the same keys and each value replaced by what the function gives. ->map_keys() changes the keys instead:

$prices = { tea: 2, cake: 3 }
echo $prices->map(fn(price) => $price * 2)                // { tea: 4, cake: 6 } because each price is doubled
echo $prices->map(fn(price, item) => "{ $item } £{ $price }") // { tea: 'tea £2', cake: 'cake £3' } because the key is passed second

->map_keys()

->map_keys(fn(key, value?)) gives a map with each key replaced by what the function gives, and the values left alone. The key comes first here, since the keys are what you are changing. When two keys turn into the same key, the later entry wins:

$form = { first_name: 'Ada', last_name: 'Lovelace' }
echo $form->map_keys(fn(key) => $key->case(camel))   // { firstName: 'Ada', lastName: 'Lovelace' }
echo { a: 1, A: 2 }->map_keys(fn(key) => $key->lower()) // { a: 2 } because both keys become a, and the later one wins

->merge()

->merge(other) adds another map’s keys to this one. Where both maps have a key, the other map’s value wins. Keys keep their first place, and new keys go on the end. Maps inside are replaced whole; ->deep_merge() merges them too:

$defaults = { port: 80, host: 'localhost' }
echo $defaults->merge({ port: 8080 })      // { port: 8080, host: 'localhost' } because the new port replaces 80
echo $defaults->merge({ secure: true })    // { port: 80, host: 'localhost', secure: true } because secure is new, so it goes last

->omit()

->omit(keys) gives a copy without the listed keys. Keys the map doesn’t have are ignored. ->pick() does the opposite. The editor offers the map’s own keys inside the brackets:

$user = { name: 'Ada', email: 'ada@example.com', password: 'secret' }
echo $user->omit([password])          // { name: 'Ada', email: 'ada@example.com' } because the password is left out
echo $user->omit([password, phone])   // { name: 'Ada', email: 'ada@example.com' } because there was no phone to leave out

->pick()

->pick(keys) gives a copy with only the listed keys, in the map’s own order rather than the order you list them. Keys the map doesn’t have are ignored:

$user = { name: 'Ada', email: 'ada@example.com', password: 'secret' }
echo $user->pick([email, name])   // { name: 'Ada', email: 'ada@example.com' } because the map's own order is kept
echo $user->pick([name, phone])   // { name: 'Ada' } because there is no phone to pick

->reduce()

->reduce(fn(total, value, key?), initial?) walks through the entries in order, building up one value. The function gets the total so far and the next value, and gives the new total. Without initial, the first value is the first total, and an empty map gives null:

$basket = { apples: 3, pears: 5, plums: 2 }
echo $basket->reduce(fn(total, count) => $total + $count)       // 10 because 3 + 5 is 8, then 8 + 2 is 10
echo $basket->reduce(fn(total, count) => $total + $count, 100)  // 110 because the total starts at 100
echo $basket->reduce(fn(list, count, fruit) => "{ $list } { $fruit }", 'Bought:') // 'Bought: apples pears plums'

->reject()

->reject(fn(value, key?)) drops the entries for which the function is true and keeps the rest. It is ->filter() the other way round:

$stock = { apples: 3, pears: 0, plums: 2 }
echo $stock->reject(fn(count) => $count == 0)   // { apples: 3, plums: 2 } because pears are at 0

->remove()

->remove(key) gives a copy without one key. A key the map doesn’t have is no error; you just get the same entries back:

$person = { name: 'Ada', age: 36 }
echo $person->remove('age')    // { name: 'Ada' }
echo $person->remove('town')   // { name: 'Ada', age: 36 } because there was no town to remove

->set()

->set(key, value) gives a copy with the key set to the value. An existing key keeps its place, and a new key goes on the end:

$person = { name: 'Ada', age: 36 }
echo $person->set('age', 37)        // { name: 'Ada', age: 37 } because age keeps its place
echo $person->set('town', 'Leeds')  // { name: 'Ada', age: 36, town: 'Leeds' } because town is new, so it goes last

->sort()

->sort(by: fn(value, key?), order?: asc|desc) gives a copy with the entries in a new order, sorted by what by gives for each one, smallest first. order: desc puts the largest first. To sort by key, have by give the key:

$votes = { tea: 5, coffee: 9, juice: 2 }
echo $votes->sort(by: fn(count) => $count)                // { juice: 2, tea: 5, coffee: 9 } because 2 is the fewest votes
echo $votes->sort(by: fn(count) => $count, order: desc)->keys()->first() // 'coffee' because it has the most votes
echo $votes->sort(by: fn(count, drink) => $drink)->keys() // ['coffee', 'juice', 'tea'] because the keys are in alphabetical order

->values()

->values() gives the values as a list, in order, so you can use list methods such as ->sum():

$basket = { apples: 3, pears: 5 }
echo $basket->values()          // [3, 5]
echo $basket->values()->sum()   // 8 because 3 + 5 is 8

Edit this page on GitHub