PHP - Sorting Associative Array Keys with ksort() and krsort()

Introduction

ksort() and krsort() behave in much the same way as asort() and arsort(), in that they sort arrays in ascending and descending order, respectively, preserving the associations between keys and values.

The only difference is that, whereas asort() and arsort() sort elements by value, ksort() and krsort() sort the elements by their keys:

Demo

<?php
         $myBook = array("title"=> "PHP",
                         "author"=> "D",
                         "year"=>  2018);

         ksort($myBook);// w ww.java 2s  .c  o  m
         print_r($myBook);

         krsort($myBook);
         print_r($myBook);
?>

Result

ksort() has sorted the array by key in ascending order ("author", "title", "year"), whereas krsort() has sorted by key in the opposite order.

Related Topic