HH\Shapes::idx

Shapes::idx is a helper function for accessing shape field value, or getting a default if it's not set - similar to idx(), but for shapes

public static function idx<T as shape()>(
  darray $shape,
  arraykey $index,
  mixed $default = NULL,
): mixed;

This behavior cannot be expressed with type hints, so it's hardcoded in the typechecker. Depending on arity, it will be one of the

idx(S $shape, arraykey $index) : ?Tv, idx(S $shape, arraykey $index, Tv $default) : Tv,

where $index must be statically known (literal or class constant), and S is a shape containing such key:

type S = shape( ... $index => Tv, ... )

Parameters

  • darray $shape
  • arraykey $index
  • mixed $default = NULL

Returns

  • mixed

Examples

This example shows how to use Shapes::idx for keys that may or may not exist in a Shape:

function run(shape('x' => int, 'y' => int, ?'z' => int) $point): void {
  // The key 'x' exists in the Shape $point so it's returned
  \var_dump(Shapes::idx($point, 'x'));

  // The key 'z' doesn't exist in $point so the default NULL is returned
  \var_dump(Shapes::idx($point, 'z'));

  // The key 'z' doesn't exist in $point so our explicit default 0 is returned
  \var_dump(Shapes::idx($point, 'z', 0));
}

run(shape('x' => 3, 'y' => -1));
Output
int(3)
NULL
int(0)

This example shows that Shapes::idx will only return the default value if the key doesn't exist in the Shape. If the key exists but is NULL then NULL will be returned.

function runNullable(shape('x' => ?int, 'y' => ?int, ...) $point): void {
  // The key 'x' exists, so its value (3) is returned, not our explicit default 0
  \var_dump(Shapes::idx($point, 'x', 0));

  // The key 'y' exists, so its value (NULL) is returned, not our explicit default 0
  \var_dump(Shapes::idx($point, 'y', 0));
}

<<__EntryPoint>>
function runNullableMain(): void {
  runNullable(shape('x' => 3, 'y' => null));
}
Output
int(3)
NULL