How to Sort an Array by Values in PHP?

Problem:

You have an array – a one-dimensional array, see the following example. You want to sort the values of array.

<?php
$languages = array(
                  "a" => "c",
                  "b" => "javascript",
                  "c" => "php",
                  "d" => "java",
                  "e" => "asp.net"
                 );
?>

Solution:

We’ll see three different solutions to sort an array. There are differences in the resulting arrays. So, pick the right one you need.

Method 1: Using sort() function

sort() function sorts values of an array in ascending order – lowest to highest. See the example below-

<pre>
<?php
$languages = array(
                  "a" => "c",
                  "b" => "javascript",
                  "c" => "php",
                  "d" => "java",
                  "d" => "asp.net"
                 );
?>
</pre>

[wpdm_file id=61]

Output:
 Array(
    [0] => asp.net
    [1] => c
    [2] => java
    [3] => javascript
    [4] => php
 )

Caution: Please note that the keys of the resulting array are rearranged. The keys in the resulting array are not same as before.

Recommendation:If don’t care about the keys, select this method.

 

Method 2: Using asort() function

asort() function also sorts values of an array in ascending order – lowest to highest. See the example below-

<pre>
<?php
$languages = array(
                  "a" => "c",
                  "b" => "javascript",
                  "d" => "php",
                  "e" => "java",
                  "f" => "asp.net"
             );
asort($languages);
print_r($languages);
?>
</pre>

[wpdm_file id=62]
Output:

Array
(
    [f] => asp.net
    [a] => c
    [e] => java
    [b] => javascript
    [d] => php
)

Recommendation: If you need to preserve the keys in the resulting array, use this method. The keys in the resulting array are same as it was before.

 

Method 3: Using arsort() function

arsort() function also sorts values of an array in descending order – highest to lowest. See the example below-

<?php
$languages = array(
                 "a" => "c",
                 "b" => "javascript",
                 "d" => "php",
                 "e" => "java",
                 "f" => "asp.net"
);
arsort($languages);
print_r($languages);
?>

Output:

Array
(   
    [d] => php   
    [b] => javascript   
    [e] => java   
    [a] => c   
    [f] => asp.net
)

Recommendation: To sort values in descending order, highest to lowest, select this method.