How to Sort an Array by Keys in PHP?

Problem:

You have an array which has some elements in it. You want to search the array by its keys.

Solution:

There are few ways you can sort an array by its keys-

Method 1: Using ksort() function

ksort() function sorts an array by keys in ascending order. See the following example-

<pre>
<?php
$age = array(
        "Peter" => 34,
        "John" => 27,
        "Smoth" => 30,
        "Jack" => 32
        );
            
if(ksort($age)) 
    print_r($age);
?>
</pre>

[wpdm_file id=85]

Output:

Array(
        [Jack] => 32
        [John] => 27
        [Peter] => 34
        [Smoth] => 30
 )
Line 9-10 After successful sorting the $age[] array by keys, ksort() function returns true, otherwise returns false. If it sorts successfully, we print the sorted array in line 10.

 

Method 2: Using krsort() function

krsort() function sorts an array by keys in reverse order. See the following example-

<pre>
<?php
$age = array(
        "Peter" => 34,
        "John" => 27,
        "Smoth" => 30,
        "Jack" => 32
        );

if(krsort($age))  print_r($age);
?>
</pre>

[wpdm_file id=85]

Output:

Array(   
        [Smoth] => 30   
        [Peter] => 34   
        [John] => 27   
        [Jack] => 32
)
Line 10-11 After successful sorting the array $age[] by keys, krsort() function returns true, otherwise false. If it sorts successfully, we print the sorted array in line 11.