doc-en icon indicating copy to clipboard operation
doc-en copied to clipboard

Strange behavior of array_multisort

Open Sekiphp opened this issue 3 years ago • 4 comments

Hello,

during investigation of PHP doc I found interesting thing in array_multisort function.

For argument rest there is written:

rest More arrays, optionally followed by sort order and flags. Only elements corresponding to equivalent elements in previous arrays are compared. In other words, the sort is lexicographical.

Sort order and flags (in this direction), but in example 2 these parameters are switched. Switching should be allowed, but only if flags value is SORT_REGULAR, but is not this case

<?php
$ar = array(
       array("10", 11, 100, 100, "a"),
       array(   1,  2, "2",   3,   1)
      );
array_multisort($ar[0], SORT_ASC, SORT_STRING,
                $ar[1], SORT_NUMERIC, SORT_DESC);
var_dump($ar);
?>

EN DOC: https://www.php.net/manual/en/function.array-multisort.php Code: https://github.com/php/php-src/blob/5d6bc25063e571da936010b1fae822f5d610deca/ext/standard/array.c#L5630

Live example: https://sandbox.onlinephpfunctions.com?s=s7EvyCjg5VJJLFKwVUgsKkqs1ODlUoAACFfJ0EBJR8HQEIgNDKCEUqKSpg6aOiADqEbBCChrBNSgoGAMIgw1Yco0rXm5wCrjc0tzSjKL84tKNIDWRhvE6igE-weFxDsGO0NZwSFBnn7uCAvgAKTeEKbeL9TXNcgTpsfFNdgZZEVZYlF8SmluAchsEN_eDgA%2C&v=7.3.5

Sekiphp avatar Mar 22 '22 14:03 Sekiphp

$array1_sort_flags says:

This argument can be swapped with array1_sort_order or omitted entirely, in which case SORT_REGULAR is assumed.

This is slightly misleading, as SORT_REGULAR is only assumed, if $array1_sort_flags is omitted (but not if the arguments are swapped).

cmb69 avatar Mar 22 '22 14:03 cmb69

Documentation does not correspond with behaviour or is not clear. After deeper investigation i realized, that items on same positions are "connected". Maybe it will be nice to add this information to the doc.

In doc is also written, that:

This argument can be swapped with array1_sort_order or omitted entirely, in which case SORT_REGULAR is assumed

But in rest you can swap and does not depends on order of these two args.

Sekiphp avatar Mar 22 '22 15:03 Sekiphp

Ran into this today as well,

image

This first parameter isn't just the reference to the array. Instead of it seems you need to pass it as the final parameter. So is this documentation reversed?

criticalfault avatar Oct 25 '24 17:10 criticalfault

@criticalfault, maybe give a simple but complete test script. I don't think there is anything wrong with the implementation of array_multisort(), nor anything grossly wrong about its documentation.

cmb69 avatar Oct 31 '24 14:10 cmb69