Chapter 5. Collections

PHP has only one built-in collection type: array. It presents an interface that is a set of ordered key/value pairs. This interface allows it to serve the purpose of several different data structures that programs in most languages typically use: vectors, sets, and maps (also known as dictionaries).

Hack has several classes that provide specialized vector, set, and map functionality. They allow for better understanding by both the Hack typechecker and human readers of code.

There are seven collection classes in Hack:

Vector

A mutable, ordered sequence of values, indexed by integers. The indices are the integers between 0 and n–1, where n is the number of elements in the vector.

Map

A mutable, ordered set of unique keys, each of which maps to a value. The keys may be integers or strings, and the values can be of any type. Unlike the map types in many other programming languages, Hack Maps remember the order in which their values were inserted. Of all the collection classes, Map is the most similar to PHP arrays.

Set

A mutable, ordered set of unique values. The values may be integers or strings.

Pair

An immutable sequence of exactly two values, indexed by the integers 0 and 1. Pairs are a detail of the API to the other collection classes, and you generally shouldn’t create them yourself; use tuples instead (see “Hack’s Type System”).

ImmVector, ImmMap, and ImmSet

Immutable versions of Vector, Map, and Set, respectively.

Vector, Map, ...

Get Hack and HHVM now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.