Tuples: Relationship To Arrays

Under the covers, in HHVM, tuples are really just restricted arrays.

Elements

You cannot change a tuple's number of elements. You can change a value of a tuple if and only if the new value is of the same type as the current value.

If you try to change a value to a value of a different type, the Hack typechecker will raise an error (however, HHVM will run without complaint since tuples are just arrays under the covers).

<?hh

namespace Hack\UserDocumentation\Tuples\RelationshipToArrays\Examples\ChgValue;

function run(): void {
  $t = tuple (3, "str", array(1, 2));
  var_dump($t);
  $t[0] = 4;
  $t[1] = "hi";
  $t[2] = array("hello", 1000);
  $t[1] = 100; // type error since [1] is originally a string
  var_dump($t);
}

run();
Output
array(3) {
  [0]=>
  int(3)
  [1]=>
  string(3) "str"
  [2]=>
  array(2) {
    [0]=>
    int(1)
    [1]=>
    int(2)
  }
}
array(3) {
  [0]=>
  int(4)
  [1]=>
  int(100)
  [2]=>
  array(2) {
    [0]=>
    string(5) "hello"
    [1]=>
    int(1000)
  }
}

Reading

You can read from a tuple using array square bracket syntax. The most common way to read from a tuple, however, is to use list() assignment.

<?hh

namespace Hack\UserDocumentation\Tuples\RelationshipToArrays\Examples\ChgValue;

function run(): void {
  $t = tuple (3, "str", array(1, 2));
  var_dump($t[1]); // literal syntax
  list($i, $s, $arr) = $t; // list assignment
  var_dump($i);
  var_dump($s);
  var_dump($arr);
}

run();
Output
string(3) "str"
int(3)
string(3) "str"
array(2) {
  [0]=>
  int(1)
  [1]=>
  int(2)
}