Monday, 13 August 2018

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-
1
2
3
4
5
6
7
8
9
10
11
12
13
<pre>
<?php
$age = array(
        "Peter" => 34,
        "John" => 27,
        "Smoth" => 30,
        "Jack" => 32
        );
             
if(ksort($age))
    print_r($age);
?>
</pre>
Output:
Line 9-10After 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-
1
2
3
4
5
6
7
8
9
10
11
12
<pre>
<?php
$age = array(
        "Peter" => 34,
        "John" => 27,
        "Smoth" => 30,
        "Jack" => 32
        );
 
if(krsort($age))  print_r($age);
?>
</pre>
Output:
Line 10-11After 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.

0 comments:

Post a Comment