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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.