How do I sort an array by key?

The key to sorting by key, is to add a k before the sort to get the function ksort.

This takes the name of the array as the parameter, and works like this: 

$myworld = array(”c”=>”best”,”a”=>”make”,”b”=>”men”);
print_r($myworld);
?>
his prints:

Array
(
[c] => best
[a] => make
[b] => men
We need to use ksort to get the right key order:

$myworld = array(”c”=>”best”,”a”=>”make”,”b”=>”men”);
ksort($myworld);
print_r($myworld);
?>

Array
(
[a] => make
[b] => men
[c] => best
)

No related posts.

Leave a Reply

XHTML: You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>