HH\Readonly\Shapes::idx

Use Readonly\Shapes::idx to retrieve a field value in a shape, when the key may or may not exist

public static function idx(
  shape(...) $shape,
  arraykey $index,
  mixed $default = NULL,
): mixed;

If $index does not exist in the shape, the default value will be returned ($default), if one has been set. It behaves similarily to idx() for Collections.

A few examples:

Use Shapes::idx when the key in your shape is optional (e.g., ?x, in shape(?'x' => int). If the key in your shape is always present, access the value directly: $my_shape['x'].

The second argument, $index must always be a literal.

Parameters

  • shape(...) $shape - shape to search for $index.
  • arraykey $index - Key ($index) to search. Must be a literal!
  • mixed $default = NULL - Default value to return if $index does not exist. By default, returns null.

Returns

  • $value - - Value at $index, if it exists, or $default.