[php-src] PR #20305: Fix #20262: SORT_REGULAR transitivity violation with mixed numeric/non-numeric strings
| From: | jmarble | Date: | Mon, 27 Oct 2025 01:56:53 +0000 |
| Subject: | [php-src] PR #20305: Fix #20262: SORT_REGULAR transitivity violation with mixed numeric/non-numeric strings | ||
| Groups: | php.git-pulls | ||
| Request: | Send a blank email to git-pulls+get-33824@lists.php.net to get a copy of this message | ||
Pull Request: https://github.com/php/php-src/pull/20305
Author: jmarble
### Problem
array_unique() with SORT_REGULAR was missing duplicates, and
sort() was incorrectly ordering equal values due to a transitivity violation in string
comparison.
When comparing numeric strings (like '5', '10') with
non-numeric strings (like '3A'), the comparison function fell back to
lexicographic comparison, which violated transitivity:
- '5' < '10' (numeric: 5 < 10)
- '10' < '3A' (lexicographic: '1' < '3')
- '5' > '3A' (lexicographic: '5' > '3')
**Violates transitivity**
This caused equal values to not be grouped together in sorted arrays.
### Solution
Fixed php_array_data_compare_unstable_i() in ext/standard/array.c to
consistently order non-numeric strings before numeric strings when one is numeric and one is not,
ensuring transitivity for all SORT_REGULAR operations.
**Important:** This fix does **NOT** change the behavior of comparison operators like
<=>, maintaining backward compatibility. The fix only affects sorting and array
operations with SORT_REGULAR, similar to how enum comparison is handled specially for sorting.
### Test Updates Required
The following tests need their expected output updated to reflect the new transitive sort order:
- ext/standard/tests/array/sort/array_multisort_basic1.phpt
- ext/standard/tests/array/sort/array_multisort_variation5.phpt
- ext/standard/tests/array/sort/array_multisort_variation6.phpt
Tests marked as "(OK to fail as result is unpredictable)" (arsort_variation11,
asort_variation11, sort_variation11, rsort_variation11) should maybe still be updated for
consistency.