Many times when you go for an interview or technical test you may find this question
"What is the difference between the sort() and asort() function in php ?"
Basically sort() and asort() functions are used to sort the array in php.
* sort() function syntax - sort(array,sorttype)
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.
Now we are applying sort function and printing the array.
so the output of the above code will be -
initial array contents -
Array ( [a] => chaprak [b] => programming [c] => dexter )
and after applying sort function -
Array ( [0] => chaprak [1] => dexter [2] => programming )
its keys are changed to numeric values and sorting is done.
View php manual for the array sort function
* 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
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 )
Tweet this!