[php-src] PR #20315: Fix SORT_REGULAR transitivity for mixed types

From: Date: Tue, 28 Oct 2025 04:27:14 +0000
Subject: [php-src] PR #20315: Fix SORT_REGULAR transitivity for mixed types
Groups: php.git-pulls 
Request: Send a blank email to git-pulls+get-33832@lists.php.net to get a copy of this message
Pull Request: https://github.com/php/php-src/pull/20315 Author: jmarble ### Problem array_unique() with SORT_REGULAR was missing duplicates, and sort() was producing inconsistent results depending on input order when comparing mixed types (numeric strings, non-numeric strings, integers, doubles). The root cause: SORT_REGULAR was using PHP's comparison operators (which are non-transitive by design) directly in sorting algorithms that **require** transitive comparisons to function correctly. When comparing these types, the comparison created cycles: - "5" < "10" (numeric: 5 < 10) - "10" < "3A" (lexicographic: '1' < '3') - "5" > "3A" (lexicographic: '5' > '3') **Creates a cycle** This violated the fundamental requirement of sorting algorithms: the comparison function must be transitive. This affected not only scalar strings but also nested arrays and objects with string properties. ### Solution Added EG(transitive_compare_mode) flag to zend_executor_globals that enforces transitive comparison during sorting operations, with consistent ordering: non-numeric < numeric-strings < numeric-types. Modified three comparison functions to check this flag: - zendi_smart_strcmp() - handles string-to-string comparisons - compare_long_to_string() - handles integer-to-string comparisons - compare_double_to_string() - handles double-to-string comparisons Used save/restore pattern in php_array_data_compare_unstable_i() to handle reentrancy correctly. **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. ### Tests Added two comprehensive tests: - sort_regular_transitive.phpt - Tests scalars, nested arrays, and array_unique() - sort_regular_transitive_objects.phpt - Tests objects with string properties ### 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) may also need updates for consistency. --- **Previous attempts:** - #20305 - #20273 This PR provides the complete solution. Fixes #20262

« previous php.git-pulls (#33832) next »