HH\Map::fromItems

Creates a Map from the given Traversable, or an empty Map if null is passed.

Description

public static function fromItems(
  ?Traversable<Pair<Tk,Tv>> $items,
): Map<Tk,Tv>

Creates a Map from the given Traversable, or an empty Map if null is passed.

This is the static method version of the Map::__construct() constructor.

Parameters

  • ?Traversable<Pair<Tk,Tv>> $items - any Traversable object from which to create a Map (e.g., array). If null, then an empty Map is created.

Return Values

Examples

This example shows that a Map can be created from any Traversable of key-value pairs:

<?hh

namespace Hack\UserDocumentation\API\Examples\Map\FromItems;

// Create a new Map from an array of key-value pairs
$m = Map::fromItems(array(
  Pair {'red', '#ff0000'},
  Pair {'green', '#00ff00'},
  Pair {'blue', '#0000ff'},
  Pair {'yellow', '#ffff00'},
));
var_dump($m);

// Create a new Map from a Vector of key-value pairs
$m = Map::fromItems(Vector {
  Pair {'red', '#ff0000'},
  Pair {'green', '#00ff00'},
  Pair {'blue', '#0000ff'},
  Pair {'yellow', '#ffff00'},
});
var_dump($m);

// An empty Map is created if null is provided
$m = Map::fromItems(null);
var_dump($m);
Output
object(HH\Map)#5 (4) {
  ["red"]=>
  string(7) "#ff0000"
  ["green"]=>
  string(7) "#00ff00"
  ["blue"]=>
  string(7) "#0000ff"
  ["yellow"]=>
  string(7) "#ffff00"
}
object(HH\Map)#11 (4) {
  ["red"]=>
  string(7) "#ff0000"
  ["green"]=>
  string(7) "#00ff00"
  ["blue"]=>
  string(7) "#0000ff"
  ["yellow"]=>
  string(7) "#ffff00"
}
object(HH\Map)#12 (0) {
}