Using PHP ksort On Alphanumeric Keys Does Not Work Correctly. Is there a way?

robdiablo
robdiablo used Ask the Experts™
on
I am trying to use the ksort function of PHP on some alphanumeric keys, however, when the array is returned, it is not sorted the way I expect.  For example:

<?php
$query = array("q123"=>"lemon", "q2"=>"orange", "q1"=>"banana", "q125"=>"apple");
ksort($query);
foreach ($query as $key => $val) {
    echo "$key = $val\n";
}
?>

The above example will output:

q1 = banana
q123 = lemon
q125 = apple
q2 = orange

Expected:

q1 = banana
q2 = orange
q123 = lemon
q125 = apple

How can I get it to sort as expected?


Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Use asort instead of ksort..
$query = array("q123"=>"lemon", "q2"=>"orange", "q1"=>"banana", "q125"=>"apple");
asort($query);
foreach ($query as $key => $val) {
    echo "$key = $val\n";
}
?>
halO Vineeth,

don u have sense?? dint u read the question?
Why Diversity in Tech Matters

Kesha Williams, certified professional and software developer, explores the imbalance of diversity in the world of technology -- especially when it comes to hiring women. She showcases ways she's making a difference through the Colors of STEM program.

Hi thiyagU,

 If u know the answer plZ post it..

Author

Commented:
Using asort will sort the array by value instead of key thus it would look like this:

q125 = apple
q1 = banana
q123 = lemon
q2 = orange

The keys are not sorted, the values are.  We need the keys to be sorted as shown in the Expected section of the question above.

Author

Commented:
Found the answer:

<?php
$query = array("q123"=>"lemon", "q2"=>"orange", "q1"=>"banana", "q125"=>"apple");
uksort($_GET, "strnatcmp");
foreach ($query as $key => $val) {
    echo "$key = $val\n";
}
?>
Hi robdiablo,

I tried your solution. But i dint get ur expected result. The below output is wat i got from the uksort function.

q123 = lemon
q2 = orange
q1 = banana
q125 = apple

Ur expected result was

q1 = banana
q2 = orange
q123 = lemon
q125 = apple
Sorry, I forgot to change $_GET to $query so it was just repeating the array without sorting it.  Here is the correct code:

<?php
$query = array("q123"=>"lemon", "q2"=>"orange", "q1"=>"banana", "q125"=>"apple");
uksort($query, "strnatcmp");
foreach ($query as $key => $val) {
    echo "$key = $val\n";
}
?>

uksort($query, "strnatcmp"); is the correct way to sort natural language strings.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial