Jump to content

natsort()... What am I missing here?


ZHarvey

Recommended Posts

Let's say I have an array:

 

$myArray[0] = "AtG2";

$myArray[1] = "AtG4";

$myArray[2] = "AtG1";

$myArray[3] = "AtG3";

$myArray[4] = "AtG5";

 

I want to sort it alphanumerically, so that the key/value pairs are as follows:

[zero*] => "AtG1"

[1] => "AtG2"

[2] => "AtG3"

[3] => "AtG4"

[4] => "AtG5"

 

* = I have to write [zero] because putting an actual zero number inside of [ and ] braces converts it to an HTML list bullet.

 

It *appears* that natsort() is the proper function for this. The only problem I'm having is that natsort() doesn't manipulate key/value pairs.  To confuse me even more, literally every example I can find on using natsort() uses it in conjunction with print_r() like so:

 

natsort($someArray);

print_r($someArray);

 

Obviously, something is happening to $someArray when passed to natsort(), otherwise, print_r() wouldn't be able to order the indices in synch with the natural ordering algorithm.

 

Well, I don't need my web app to use print_r()! I just need the darn key/value pairs reordered so that when I echo $myArray[3], I know I'm going to get "AtG4".

 

What am I missing here? What is the point of calling it a "sort" if it doesn't manipulate the key/value pairs??? How can I get what I want?!?

Link to comment
https://forums.phpfreaks.com/topic/212220-natsort-what-am-i-missing-here/
Share on other sites

AbraCadaver,

 

Yes the print_r() prints them via natural ordering algorithm correctly. But since natsort() doesn't change key/value pairs, if you just for-loop through the array, it will appear to be unsorted!

 

Shawn,

 

Thank you it *looks* like that was what I needed (array_values, didn't even know it existed).

 

Personally, I think that's the first aspect of PHP that I dislike so far, and I've been coding in PHP for almost a year now. It is insane to me that an array sorting function doesn't actually reorder the elements in the array.  I can't think of another language that operates like this.

 

Thanks for the suggestions and input everyone!

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.