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
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!

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.