Other Features: Placeholder Variable

There are times when you are using a paradigm that returns multiple values (e.g., list() or foreach) where you don't care about one or more of those values. The placeholder variable operator allows you to use these paradigms without having to create dummy variables that will never be used.

This is the placeholder variable:

$_

You can use the placeholder variable when iterating over a key/value pair, but you don't care, for example, about the value of that pair.

<?hh

namespace Hack\UserDocumentation\Operators\PHV\Examples\Iteration;

function phv_iteration(): void {
  $m = Map {'a' => 1, 'b' => 2, 'c' => 3 };
  // Don't care about the values
  foreach ($m as $key => $_) {
    var_dump($key); // dumps 'a', 'b', 'c'
  }
}

phv_iteration();
Output
string(1) "a"
string(1) "b"
string(1) "c"

Another common case for the placeholder variable is when you are using list() and you don't care about one or more of the variables that are being set.

<?hh

namespace Hack\UserDocumentation\Operators\PHV\Examples\Iteration;

function phv_list(): void {
  $v = Vector {1, 2, 3};
  // Don't care about the middle value.
  list($a, $_, $b) = $v;
  var_dump($a);
  var_dump($b);
}

phv_list();
Output
int(1)
int(3)

Typechecker Semantics

The type of $_ is void. This allows the typechecker to treat this operator with the same rules as it would for anything of type void. This is how the typechecker can ensure that the value associated with the placeholder is not actually being used in a read context, for example.

<?hh

namespace Hack\UserDocumentation\Operators\PHV\Examples\Iteration;

function phv_iteration(): void {
  $m = Map {'a' => 1, 'b' => 2, 'c' => 3 };
  // Don't care about the values
  foreach ($m as $key => $_) {
    var_dump($key); // dumps 'a', 'b', 'c'
    var_dump($_); // can't do this
  }
}

phv_iteration();