ZHarvey Posted August 31, 2010 Share Posted August 31, 2010 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?!? Quote Link to comment Share on other sites More sharing options...
Pikachu2000 Posted August 31, 2010 Share Posted August 31, 2010 Have you tried it without using print_r()? Quote Link to comment Share on other sites More sharing options...
AbraCadaver Posted August 31, 2010 Share Posted August 31, 2010 natsort() preserves the key/value relationship and it sounds like you want them reordered? natsort($someArray); $someArray = array_values($someArray); Quote Link to comment Share on other sites More sharing options...
ZHarvey Posted August 31, 2010 Author Share Posted August 31, 2010 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! Quote Link to comment 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.