HH\Shapes::idx

Description

public static function idx(
  array $shape,
  arraykey $index,
  $default = null,
)

Parameters

  • array $shape
  • arraykey $index
  • $default = null

Examples

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

<?hh

namespace Hack\UserDocumentation\API\Examples\HH\Shapes\Idx;

function run(): void {
  $point = shape('x' => 3, 'y' => -1);

  // 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();
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.

<?hh

namespace Hack\UserDocumentation\API\Examples\HH\Shapes\Idx;

function runNullable(): void {
  $point = shape('x' => 3, 'y' => null);

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

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

runNullable();
Output
int(0)
NULL