samshel Posted February 29, 2012 Share Posted February 29, 2012 Hi, Following is the problem i am facing. Any help would be greatly appreciated. I have an associative array: array(5) { [66]=> int(1) [244]=> int(1) [181]=> int(1) [256]=> int(1) [233]=> int(1) } If i run arsort on this array, it returns me the following result: array(5) { [233]=> int(1) [256]=> int(1) [181]=> int(1) [244]=> int(1) [66]=> int(1) } Since values of all elements are same (1), it should return the array as it is. However looks like arsort reverses the order of elements if the values are same. Above example is just one use case. In cases where the values are different, it returns correct results. Quote Link to comment https://forums.phpfreaks.com/topic/257999-help-on-arsort/ Share on other sites More sharing options...
creata.physics Posted February 29, 2012 Share Posted February 29, 2012 That's because arsort reverses the order. By what you've said it seems you want to use asort() Also check the user contributed notes on the asort() page on the manual, it seems somebody posted a workaround using array_multisort that would do exactly what you need. source: http://php.net/manual/en/function.asort.php Quote Link to comment https://forums.phpfreaks.com/topic/257999-help-on-arsort/#findComment-1322449 Share on other sites More sharing options...
kicken Posted February 29, 2012 Share Posted February 29, 2012 Since values of all elements are same (1), it should return the array as it is. However looks like arsort reverses the order of elements if the values are same. PHP makes no guarantee what order elements end up in if there values are the same: If any of these sort functions evaluates two members as equal then the order is undefined (the sorting is not stable). If for some reason you need them to remain in a particular order, you'll have to sort them some other way. I don't see how it should make any bit of difference though. Quote Link to comment https://forums.phpfreaks.com/topic/257999-help-on-arsort/#findComment-1322453 Share on other sites More sharing options...
samshel Posted February 29, 2012 Author Share Posted February 29, 2012 Thanks for the replies. I worked around using array_multisort. It worked. Quote Link to comment https://forums.phpfreaks.com/topic/257999-help-on-arsort/#findComment-1322496 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.