-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Description
This is a part of the Hack array proposal
Indexing for Hack arrays will have stricter semantics when using square brackets to match the behavior of Hack Collections.
No Coercion of Keys
When indexing or setting a key of an array, PHP sometimes coerces a value to either an int
or string
. Hack arrays should not do this. Indexing a Hack array with an invalid key type results in an exception. This also means int-like strings will not be converted to ints.
// These will result in exceptions for Hack arrays
$harray[0.0];
$harray[false];
// The string '0' will not be converted to the int 0
$harray['0'];
Throw on Non-existent Keys
Accessing an non-existent key for a PHP array results in raising a E_NOTICE
and returning null
. Hack arrays will throw an exception if you attempt to access an element that is not present.
Safe-Indexing
If you do not want to risk an exception being thrown when indexing into a Hack array then you can index using curly braces. Currently indexing with curly braces is the same as indexing with square brackets for PHP arrays. We will slightly change this behavior to return null
when the key is not set, but NOT raise a E_NOTICE
.
$dict = dict[];
$x = $dict{0}; // $x will be null
$y = $dict[0]; // Exception thrown since 0 is not set
This is meant to emulate the get
methods that the various Collection APIs provide.