What is the difference between the sort() function and asort() function in php ?
Basically, sort() and asort() functions are used to sort the array in php.
Sort Array in Ascending Order – sort()
Syntax
sort(array,sorting type);
sort type 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
<?php
$a = array(1,3,5,8,2);
sort($a);
?>
Sort the elements of the $a array in ascending numerical order:
so the output of the above code will be –
Array ( [0] => 1 [4] => 2 [1] => 3 [2] => 5 [3] => 8 )
asort() Function
The asort() function sorts an associative array in ascending order, according to the value.
Syntax
asort(array,sortingtype);
sorttype is Optional. Specifies how to sort the array values.
- 0 = SORT_REGULAR – Default. Compare items normally (don’t change types)
- 1 = SORT_NUMERIC – Compare items numerically
- 2 = SORT_STRING – Compare items as strings
- 3 = SORT_LOCALE_STRING – Compare items as strings, based on current locale
- 4 = SORT_NATURAL – Compare items as strings using natural ordering
<?php
$a = array(1,3,5,8,2);
asort($a);
?>
The asort() function sorts an array by the values. The values keep their original keys (index).
so the output of the above code will be –
Array ( [0] => 1 [4] => 2 [1] => 3 [2] => 5 [3] => 8 )
If you have any query or suggestions, feel free to ask me via the comment section below.
must watch some other topics :
0 Comments