Skip to content

Know whether an array shape knows the order of its keys - #7279

Open
ondrejmirtes wants to merge 6 commits into
2.3.xfrom
array-shape-key-order
Open

ondrejmirtes wants to merge 6 commits into
2.3.xfrom
array-shape-key-order

Conversation

@ondrejmirtes

@ondrejmirtes ondrejmirtes commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

ConstantArrayType stands both for literal arrays, whose key order is known (['a', 'b'] === ['b', 'a'] is always false), and for array shapes written in PHPDoc, which only say which keys are present. This adds a key-order flag to ConstantArrayType instead of a subclass or an accessory type:

  • PHPDoc shapes with explicit keys (LateResolvableArrayShapeType) are built without a known order. Literal arrays, lists, and shapes with fewer than two keys know their order (isKeyOrderKnown()).
  • equals() compares unordered shapes by their key map.
  • Template inference for non-covariant templates forgets the key order of the inferred shapes (TemplateTypeHelper::generalizeInferredTemplateType). This fixes the invariant Box<array{t: string, a: int}> vs Box<array{a: int, t: string}> case without bleeding edge.
  • isSuperTypeOf() / accepts(): an unordered shape covers every order of its keys (Yes). An ordered shape against an unordered one with the same keys is Maybe. Two shapes that both know their order and list their shared keys in different orders are No, so ['a' => 1, 'b' => 2] and ['b' => 2, 'a' => 1] are no longer supertypes of each other (Union of two literal arrays with the same keys in a different order keeps only one key order phpstan#15679).
  • TypeCombinator::union() of an ordered shape and an unordered one with the same keys is unordered: when the unordered one holds the ordered one, it is the result; when the ordered one has the wider values, it holds the other once it forgets its key order (array{start: mixed, ...} from code absorbs array{start: float, ...} from PHPDoc, as before this PR). intersect() keeps the ordered one. remove() of an ordered shape from an unordered one leaves the unordered shape.
  • === between shapes where either side's order is unknown is compared key by key and is bool, never constant true. Literal arrays with different key orders stay false.
  • The order is kept by recreate(), the builder and the combinator rules. The (unordered) marker appears only in the cache description, so error messages do not change.

Code that depends on the order now uses the flag:

  • getFirstIterableKeyType(), getLastIterableKeyType(), getFirstIterableValueType() and getLastIterableValueType() are no longer deprecated (add array_first and array_last return type extensions #4499 deprecated them because PHPDoc shapes do not enforce the order). An array that knows its key order answers with its first or last key or value, an unordered one with the union. array_key_first(), array_key_last(), array_first(), array_last(), reset(), end(), array_pop() and array_shift() use them again, so array_key_first(['a' => 1, 'b' => 2]) is 'a' while array_key_first($phpDocShape) stays 'a'|'b'. For a list, array_key_first() is 0.
  • array_search() (searchArray()) stops at the first key that surely matches when the key order is known: array_search(1, ['a' => 1, 'b' => 1]) is 'a'. An unordered shape still answers with every matching key.
  • ConstantArrayTypeBuilder::createEmpty() starts without a known key order; makeKeyOrderKnown() turns it on (like makeUnsealed()), createFromConstantArray() inherits it. Literal arrays, constant values, PHPDoc constant expressions, lists (explode(), range(), preg_split(), sscanf(), array_fill(), enum cases()), regex matches, compact(), array_combine() and rebuilt intersections mark the order known; array_filter(), array_column(), array_replace(), array_unshift() and the general-array intersection keep the order of their source, so array_column($phpDocShapeOfRows, 'id') is array{1|2, 1|2}, not array{1, 2}. With bleeding edge, values appended in no known order make a list only maybe. get_defined_vars() no longer claims an order (PHP orders variables by first mention, which the scope does not track). Loop widening keeps the order of two shapes listing the same keys in the same order (ConstantArrayType::getKeyTypesInMergedOrderWith()), and forgets it otherwise.
  • foreach unrolling is unchanged: shapes are unrolled by key in their written order, as before.

Merging shapes (TypeCombinator::union() generalization, joins of branches, SharedKeyShapeWidening) keeps an interleaved key order when both shapes list their shared keys in the same order, and forgets the order otherwise, so literal arrays with the same keys in different orders merge into one unordered shape. Intersections take the order of the first shape that knows it. TypeCombinatorTest marks unordered shapes with (unordered) and covers these merges.

Positional operations answer without a key order for unordered shapes (phpstan/phpstan#11600): getKeysArray() / getValuesArray() put any key or value (and the unsealed extras) at every position; array_pop() / array_shift() make every key optional; array_slice(), array_reverse(), array_splice() and array_chunk() without preserved keys, implode(), array_combine(), array_merge() and array spread no longer assume the written order. Literal arrays and lists keep their exact answers.

With bleeding edge, a PHPDoc shape with explicit keys is no longer a list: array{0: int, 1: string} only says the keys 0 and 1 are present, so it is a list only maybe, decided as if its keys came sorted (array{1: string, 0: int} too, while array{0: int, 2: string} never is). array{int, string}, list{0: int, 1?: string} and array{0: int, 1: string}&list stay lists, with their keys in ascending order, and a list that has to name its keys describes itself as list{...}. Without bleeding edge nothing changes here.

To keep count() narrowing for such shapes, it now narrows every sealed shape that is not a list: a count equal to the number of required keys drops the optional ones, and a count equal to the number of all keys makes every key present (array{a: int, b?: string} with count() === 1 is array{a: int}).

turbo-ext: the same in ConstantArrayType, ConstantArrayTypeBuilder, TemplateConstantArrayType, LateResolvableArrayShapeType, TemplateTypeHelper, InitializerExprTypeResolver, CountNarrowingHelper, UnionType, IntersectionType, StaticType, ConstantArrayTypeBuilder, ArrayType, MutatingScope, FuncCallScopeEffectsHelper, PhpClassReflectionExtension, ConstantTypeHelper and the late-resolvable trait.

Supersedes #7274.

Closes phpstan/phpstan#15908
Closes phpstan/phpstan#11600
Closes phpstan/phpstan#15679

@ondrejmirtes
ondrejmirtes force-pushed the array-shape-key-order branch 10 times, most recently from 497620a to 8e0ab07 Compare December 2, 2026 20:34
ConstantArrayType stands both for literal arrays, whose key order is
known, and for array shapes written in PHPDoc, which only list the keys
that are present. It now carries a key-order flag.

- ConstantArrayTypeBuilder::createEmpty() starts without a known key
  order. Builders of literal arrays, lists, constant expressions and
  functions that build arrays in a known order call makeKeyOrderKnown(),
  createFromConstantArray() keeps the order knowledge of its source, and
  functions that copy their input (array_filter(), array_column(),
  array_replace(), array_merge(), ...) know the order only when their
  inputs do.
- equals() compares unordered shapes by their key map, so two PHPDoc
  shapes that differ only in key order are the same type.
- Two arrays whose keys come in different orders are never the same
  array: isSuperTypeOf() and accepts() between shapes that know different
  key orders answer No, and Maybe when an ordered shape meets one with the
  same keys whose order is unknown. === between shapes whose order is
  unknown is bool, not always false.
- A union of shapes in different orders, or of a shape that knows its
  order with one that does not, merges into a shape that does not know
  its key order, and is not a list unless both are. A merge of shapes
  that list their shared keys in one order keeps the keys only one of
  them has where that one lists them.
- An intersection knows its key order only when one of the shapes that
  knows its order lists every key of it.
- Template inference for non-covariant templates forgets the key order of
  the inferred shapes, so Box<array{t: string, a: int}> is accepted for
  Box<array{a: int, t: string}>.
- Loop widening keeps the key order of two shapes that list the same keys
  in the same order, and forgets it otherwise.

turbo-ext: the same in the shadowed classes.

Amp-Thread-ID: https://ampcode.com/threads/T-01a230f4-34d7-76c1-abde-c90173e47a85
getFirstIterableKeyType(), getLastIterableKeyType(),
getFirstIterableValueType() and getLastIterableValueType() were
deprecated because array shapes from PHPDoc do not say in which order
their keys come. ConstantArrayType now answers them with the union of
its keys or values when it does not know its key order, and with the
first or last ones when it does, so they are no longer deprecated.

array_key_first(), array_key_last(), array_first(), array_last(),
reset(), end(), array_pop() and array_shift() use them again, and
UnionType, IntersectionType, StaticType and late-resolvable types
delegate to them instead of to getIterableKeyType() and
getIterableValueType().

turbo-ext: the same in ConstantArrayType, UnionType, IntersectionType,
StaticType and the late-resolvable trait.

Amp-Thread-ID: https://ampcode.com/threads/T-01a230f4-34d7-76c1-abde-c90173e47a85
…t do not know it

A PHPDoc array shape lists the keys that are present, not the order in
which they come. Popping, shifting, slicing, reversing, splicing,
chunking, taking the keys or values, imploding, combining, merging,
spreading and taking a column of such a shape no longer assume the
written order: every position can hold any of its keys, or any of its
extras when the shape is unsealed. Literal arrays and lists keep their
exact answers.

A shape with only integer keys renumbered by position knows its key
order again, so array_merge(), array_combine() and unpacking of such
shapes keep it.

turbo-ext: the same in ConstantArrayType and
InitializerExprTypeResolver.

Amp-Thread-ID: https://ampcode.com/threads/T-01a230f4-34d7-76c1-abde-c90173e47a85
A count equal to the number of required keys rules out every optional
key, and a count equal to the number of all keys makes every one of
them present, whatever the keys and in whatever order they come.

turbo-ext: the same in CountNarrowingHelper.

Amp-Thread-ID: https://ampcode.com/threads/T-01a230f4-34d7-76c1-abde-c90173e47a85
…edge

array{0: int, 1: string} says that the keys 0 and 1 are present, not
that they come in this order, so [1 => 'a', 0 => 1] fits it too. With
bleeding edge such a shape is a list only maybe, when its keys sorted
could form one, and a list that has to name its keys describes itself
as list{...}. list{...} and array{...}&list keep being lists, with
their keys in ascending order. Likewise, values appended to a builder
in no known order make a list only maybe.

turbo-ext: the same in ConstantArrayType, ConstantArrayTypeBuilder and
LateResolvableArrayShapeType.

Amp-Thread-ID: https://ampcode.com/threads/T-01a230f4-34d7-76c1-abde-c90173e47a85
@ondrejmirtes
ondrejmirtes force-pushed the array-shape-key-order branch from 8e0ab07 to 067ff00 Compare December 3, 2026 09:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant