Difference Between sort() and asort() in PHP

In this tutorial i will tell you difference between sort() and asort() php function.Basicly this is very common question for intrview preperation.

The function sort() and asort() functions are used to sort the array in php.
asort are use to sorts an array by the values but keep their original keys whereas sort doen’t keep their original keys.

sort(): function syntax – sort(array,sorttype)

Parameters :
sorttype – is Optional. Specifies how to sort the array values.
SORT_REGULAR – Default. Treat values as they are (dont change types)
SORT_NUMERIC – Treat values numerically
SORT_STRING – Treat values as strings
SORT_LOCALE_STRING – Treat values as strings, based on local settings

This function assigns new keys for the elements in the array. Existing keys will be deleted.

eg. See the code below when we create array $myarray we have assigned keys as a b & c.
Now we are applying sort function and printing the array.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
<?php  
$my_array = array("a" => "chaprak", "b" => "programming", "c" => "dexter");  
  
print_r($my_array);  
echo "  
";  
sort($my_array);  
echo "  
";  
print_r($my_array);  
echo "  
";  
?>

so the output of the above code will be –
initial array contents –

Select Code
1
Array ( [a] => chaprak [b] => programming [c] => dexter )

and after applying sort function –

Select Code
1
Array ( [0] => chaprak [1] => dexter [2] => programming )

its keys are changed to numeric values and sorting is done.

asort() function syntax – asort(array,sorttype)

The asort() function sorts an array by the values. The values keep their original keys (index).

sorttype is Optional. Specifies how to sort the array values.

SORT_REGULAR – Default. Treat values as they are (don’t change types)
SORT_NUMERIC – Treat values numerically
SORT_STRING – Treat values as strings
SORT_LOCALE_STRING – Treat values as strings, based on local settings

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
<?php  
$my_array = array("a" => "chaprak", "b" => "programming", "c" => "dexter");  
echo "  
";  
print_r($my_array);  
echo "  
";  
asort($my_array);  
echo "  
";  
print_r($my_array);  
?>

when we execute above code then it will produce the following output

initially array contents are – Array ( [a] => chaprak [b] => programming [c] => dexter )

after applying asort() function the contents are –

Array ( [a] => chaprak [c] => dexter [b] => programming )

see here sorting is done and even index is maintained.

  • udayanathan

    Very useful for the beginners like me.