Skip to content

Fix #11569: PHPStan does not handle ksort#5071

Closed
phpstan-bot wants to merge 1 commit intophpstan:2.1.xfrom
phpstan-bot:create-pull-request/patch-jwrbf64
Closed

Fix #11569: PHPStan does not handle ksort#5071
phpstan-bot wants to merge 1 commit intophpstan:2.1.xfrom
phpstan-bot:create-pull-request/patch-jwrbf64

Conversation

@phpstan-bot
Copy link
Collaborator

Summary

PHPStan did not reorder constant array keys after ksort()/krsort() calls. This meant that subsequent operations like array_values() returned values in the wrong order, causing false positives when the values were used with array_combine().

Changes

  • Split ksort and krsort out of the general "sort without preserving list" handler in src/Analyser/NodeScopeResolver.php
  • Added new getArrayKsortFunctionType() method that sorts ConstantArrayType entries by their key values using PHP's natural comparison (<=>)
  • Correctly computes isList for sorted arrays: ksort on a list preserves list status (keys already sequential), krsort on a list correctly marks it as non-list
  • Handles optional keys by remapping their indices after sorting
  • Updated existing test expectations in tests/PHPStan/Analyser/nsrt/bug-10627.php to match correct behavior

Root cause

The getArraySortDoNotPreserveListFunctionType() method handled all non-list-preserving sort functions identically, simply recreating the ConstantArrayType with the same key/value order. For ksort/krsort, the key order is deterministic and should be reflected in the type. Without reordering, array_values() after ksort() would produce values in the original insertion order rather than the key-sorted order, leading to incorrect types downstream.

Test

Added tests/PHPStan/Analyser/nsrt/bug-11569.php testing:

  • ksort on array{name: string, age: int} produces array{age: int, name: string} (alphabetical key order)
  • krsort reverses key order
  • array_values() after ksort returns values in the correct sorted order
  • array_combine() with sorted values produces the correct result type
  • Integer key arrays: ksort preserves order, krsort reverses
  • String key arrays: both ksort and krsort sort correctly

Fixes phpstan/phpstan#11569

- ksort/krsort now reorder ConstantArrayType entries by key value
- After ksort, array_values() returns values in the correct sorted order
- Correctly computes isList for sorted arrays (ksort on a list stays a list)
- Updated existing bug-10627 test expectations to match correct behavior
- New regression test in tests/PHPStan/Analyser/nsrt/bug-11569.php

Closes phpstan/phpstan#11569
@staabm staabm closed this Feb 28, 2026
@VincentLanglet VincentLanglet deleted the create-pull-request/patch-jwrbf64 branch March 8, 2026 12:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants