====== PHP RFC: Generic arrays ====== * Version: 0.1 * Date: 2016-02-13 * Author: Rasmus Schultz * Status: Draft * First Published at: http://wiki.php.net/rfc/generic-arrays ===== Introduction ===== This RFC is supplemental to the [[https://wiki.php.net/rfc/generics|generics RFC]]. This RCF proposes the addition of generic arrays and enhancements to array-related functions. TBD: should generic versions of the standard (SPL) collection types in PHP be part of this RFC? ===== Proposal ===== This RFC proposes the addition of two generic, type-checked countersparts to the built-in ''array'' type: one with a value type, and one with key and value types. The ''array'' keyword is overloaded, such that the following will work as expected: $counts = array(); // array $counts["kittens"] = 12; $versions = array(); // array $versions["php"] = 7.1; Violating the key or value type of a type-checked array will trigger a ''TypeError''. The actual type-checks or type-conversions performed will depend on the ''strict_mode'' flag and normal type conversion rules. Note that there is no generic form of the short array syntax - generic arrays can only be created explicitly by using the ''array'' keyword. === Array Type-casting === Generic arrays can be explicitly [[http://php.net/manual/en/language.types.array.php#language.types.array.casting|type-cast]] using the following syntax: $array = [1,2,3]; $numbers = (array) $array; In this example, the array is fully copied, and every element is type-checked, because ''int'' is a less general element type than ''mixed''. Casting to a less general index or element type than that of the source array, results in creation of a new array, and keys/elements being copied. If an index or element in the source array is incompatible with the index or element types of the created generic array, a ''TypeError'' is triggered. If an array is cast to a more general (or identical) index and element type, a lazy reference to the source array is made, identical to how PHP arrays normally work internally. The following results in an implicit type-cast: function tally(array $numbers) { // ... } tally([7,8,9]); In this case, the implicit type-cast is successful. In a case where the conversion fails, a ''TypeError'' is thrown. === Reification === TODO describe reification of generic type arguments, describe ''array_type()'' and ''array_key_type()'' functions. ===== Backward Incompatible Changes ===== No BC breaks are expected from this proposal. ===== Proposed PHP Version(s) ===== TBD ===== Proposed Voting Choices ===== For this proposal to be accepted, a 2/3 majority is required. ===== Patches and Tests ===== No patch has been written for this RFC.