Jump to content

Help on arsort


samshel

Recommended Posts

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.

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/257999-help-on-arsort/
Share on other sites

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

Link to comment
https://forums.phpfreaks.com/topic/257999-help-on-arsort/#findComment-1322449
Share on other sites

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.

 

Link to comment
https://forums.phpfreaks.com/topic/257999-help-on-arsort/#findComment-1322453
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.